Functions, Conditionals & Predicates

Similar documents
Recursion & Iteration

Functional programming with Common Lisp

Common LISP-Introduction

Introduction to LISP. York University Department of Computer Science and Engineering. York University- CSE V.

Review of Functional Programming

Imperative, OO and Functional Languages A C program is

Common Lisp. Blake McBride

Lecture Notes on Lisp A Brief Introduction

Lambda Calculus and Lambda notation in Lisp II. Based on Prof. Gotshalks notes on Lambda Calculus and Chapter 9 in Wilensky.

Fall Semester, The Metacircular Evaluator. Today we shift perspective from that of a user of computer langugaes to that of a designer of

CSCI337 Organisation of Programming Languages LISP

Announcement. Overview. LISP: A Quick Overview. Outline of Writing and Running Lisp.

Lisp Basic Example Test Questions

Symbolic Programming. Dr. Zoran Duric () Symbolic Programming 1/ 89 August 28, / 89

Functional Programming. Pure Functional Programming

A little bit of Lisp

LISP. Everything in a computer is a string of binary digits, ones and zeros, which everyone calls bits.

INF4820: Algorithms for Artificial Intelligence and Natural Language Processing. More Common Lisp

Introduction to ACL2. CS 680 Formal Methods for Computer Verification. Jeremy Johnson Drexel University

CS61A Midterm 2 Review (v1.1)

Allegro CL Certification Program

Modern Programming Languages. Lecture LISP Programming Language An Introduction

Chapter 1. Fundamentals of Higher Order Programming

Documentation for LISP in BASIC

Common LISP Tutorial 1 (Basic)

Lisp. Versions of LISP

An introduction to Scheme

Scheme Tutorial. Introduction. The Structure of Scheme Programs. Syntax

CSE 413 Midterm, May 6, 2011 Sample Solution Page 1 of 8

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives

Functional Programming - 2. Higher Order Functions

FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 2. ÚVOD DO LISPU: ATOMY, SEZNAMY, FUNKCE,

Computer Science 21b (Spring Term, 2015) Structure and Interpretation of Computer Programs. Lexical addressing

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

INF4820. Common Lisp: Closures and Macros

Functional Programming. Pure Functional Languages

Functional Programming

Functional Programming. Pure Functional Languages

CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters.

Pattern Matching WIlensky Chapter 21

User-defined Functions. Conditional Expressions in Scheme

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

15 Unification and Embedded Languages in Lisp

Streams, Delayed Evaluation and a Normal Order Interpreter. CS 550 Programming Languages Jeremy Johnson

CS 480. Lisp J. Kosecka George Mason University. Lisp Slides

FP Foundations, Scheme

Functional Programming. Big Picture. Design of Programming Languages

CS 314 Principles of Programming Languages. Lecture 16

6.184 Lecture 4. Interpretation. Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson

Below are example solutions for each of the questions. These are not the only possible answers, but they are the most common ones.

CS 314 Principles of Programming Languages

A Brief Introduction to Scheme (II)

Midterm Examination (Sample Solutions), Cmput 325

Lisp: Question 1. Dr. Zoran Duric () Midterm Review 1 1/ 13 September 23, / 13

Scheme in Scheme: The Metacircular Evaluator Eval and Apply

Programming Languages

Scheme Quick Reference

Notes on Higher Order Programming in Scheme. by Alexander Stepanov

Lecture #5 Kenneth W. Flynn RPI CS

Principles of Programming Languages 2017W, Functional Programming

Basics of Using Lisp! Gunnar Gotshalks! BLU-1

Why do we need an interpreter? SICP Interpretation part 1. Role of each part of the interpreter. 1. Arithmetic calculator.

Gene Kim 9/9/2016 CSC 2/444 Lisp Tutorial

INF4820: Algorithms for Artificial Intelligence and Natural Language Processing. Common Lisp Fundamentals

Lambda Calculus. Gunnar Gotshalks LC-1

Scheme Quick Reference

April 2 to April 4, 2018

CIS4/681 { Articial Intelligence 2 > (insert-sort '( )) ( ) 2 More Complicated Recursion So far everything we have dened requires

Heap storage. Dynamic allocation and stacks are generally incompatible.

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives

An Introduction to Scheme

CS 314 Principles of Programming Languages

Using Symbols in Expressions (1) evaluate sub-expressions... Number. ( ) machine code to add

More Scheme CS 331. Quiz. 4. What is the length of the list (()()()())? Which element does (car (cdr (x y z))) extract from the list?

CS 342 Lecture 7 Syntax Abstraction By: Hridesh Rajan

Vectors in Scheme. Data Structures in Scheme

MORE SCHEME. 1 What Would Scheme Print? COMPUTER SCIENCE MENTORS 61A. October 30 to November 3, Solution: Solutions begin on the following page.

11/6/17. Functional programming. FP Foundations, Scheme (2) LISP Data Types. LISP Data Types. LISP Data Types. Scheme. LISP: John McCarthy 1958 MIT

Building a system for symbolic differentiation

CS 314 Principles of Programming Languages

Organization of Programming Languages CS3200/5200N. Lecture 11

Symbols are more than variables. Symbols and Property Lists. Symbols are more than variables. Symbols are more than variables.

Evaluating Scheme Expressions

Intro. Scheme Basics. scm> 5 5. scm>

Introduction to Functional Programming and basic Lisp

Interpreters and Tail Calls Fall 2017 Discussion 8: November 1, 2017 Solutions. 1 Calculator. calc> (+ 2 2) 4

A Brief Introduction to Scheme (I)

Chapter 15 Functional Programming Languages

19 Machine Learning in Lisp

Scheme: Data. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, Glenn G.

Type-checking on Heterogeneous Sequences

Scheme. Functional Programming. Lambda Calculus. CSC 4101: Programming Languages 1. Textbook, Sections , 13.7

Lambda Calculus see notes on Lambda Calculus

Introduction to Scheme

Imperative languages

Lambda Calculus LC-1

(penguin-rule (if (animal-x is bird) (animal-x can swim)) (then (animal-x is penguin))) (?x is bird)

CSC 533: Programming Languages. Spring 2015

Lexical vs. Dynamic Scope

LECTURE 16. Functional Programming

Transcription:

Functions, Conditionals & Predicates York University Department of Computer Science and Engineering 1

Overview Functions as lambda terms Defining functions Variables (bound vs. free, local vs. global) Scoping (static vs. dynamic) Predicates Conditionals [ref.: Wilensky Chap 3 4 ] 2

Functions as lambda terms In lambda calculus, function f(x)=x 2 is written as ( x.(* x x)) In LISP it is written as: (lambda (x) (* x x)) In lambda calculus, an application of above function to 5 is written as (( x.(* x x)) 5) In LISP, it is written as ((lambda (x) (* x x)) 5) York University CSE 3401 V. Movahedi 3

Functions as lambda terms In the LISP interpreter environment, we type in a lambda term for evaluation ( reduction). If we write a list for evaluation, the first element is always assumed to be a function (We input a redex). > ((lambda (x) (* x x)) 5) 25 > ((lambda (x y) (cons x y)) 1 (2 3 4)) (1 2 3 4) A redex: A lambda abstraction applied to a term It is not convenient to write the lambda definition of functions every time we need them, therefore we can give them names using defun. York University CSE 3401 V. Movahedi 4

Defining Functions Defining functions using defun > (defun half(x) (/ x 2)) HALF > (half 3) 3/2 > (defun average (x y) (/ (+ x y) 2.0)) AVERAGE > (average 3 2) 2.5 Formal parameters x and y above are formal parameters of function definition of average Formal parameters must be symbols The value of formal parameters is not confused with their value outside the definition 5

More generally... Function definition: (defun fname (p1 p2...pn) (... body 1...) (... body 2...)... (... body m...)) Calling above function (fname a1 a2...an) Evaluation: (1) Definition of fname is retrieved (2) Supplied arguments a1...an are evaluated to get actual arguments b1...bn (3) Formal arguments p1...pn are assigned actual arguments b1...bn respectively (4) Each code in body 1 to body m is evaluated in the order (5) The value returned by body m is returned. 6

Bound vs. free variables > (setq x 5) 5 > (defun funone (x) (* x 2)) FUNONE > (funone 6) 12 > x 5 > (defun funtwo (y) (* x y)) FUNTWO > (funtwo 6) 30 > y Error! Variable Y has no value x is the formal parameter of funone and is a bound variable Value of x at top level does not change. X is NOT the formal parameter of funtwo and therefore is free here. Its value is the same as top level. 7

Bound vs. free (cont.) > (setq sum 0) 0 > (defun getsum(x) (setq y 10) (setq sum (+ x y))) > (getsum 5) 15 > sum 15 > y 10 x is bound, y and sum are free Changes to free variables are NOT local to a function! setq creates a variable at top level! 8

Bound vs. free (cont.) Each time a function is called, a new variable is created for each formal parameter. Changing value of formal parameters does not effect value of symbols with the same name at interpreter level (top level). Formal parameters are bound variables. A symbol (variable) used in definition of a function that is not a formal parameter of the function is a free variable. Changing value of free variables changes their value at top level. 9

Local vs. global variables Bound variables are local variables, can only be accessed inside function calls. A variable at the top level (interpreter level) is a global variable. It can be accessed at the top level, or inside function calls. Free variables refer to the same global variables at top level. If setq is used with free variables, it can create global variables, or change value of existing ones! Do not use inside function definitions unless you intentionally want global effect. Not a good idea! 10

Let and Let* Use let for temporary binding (let ((var1 value1) (var2 value2)... (varm valuem)) (body1) (body2)... (bodyn)) The value returned by body n is returned Let assigns all values in parallel, use let* if you need sequential assignment Example > (defun getsum(x) (let ((z 10)) (+ x z))) > (getsum 10) 20 > z Error! Variable z has no value z is bound temporarily inside let. No global variable z! 11

Static vs. Dynamic Scoping Scoping referring to the method of choosing which variable is referenced by a symbol inside a function 1. Static (or lexical) scoping: A given symbol refers to a variable in its local environment, and depends on the function definition in which it is accessed. 2. Dynamic scoping: A given symbol refers to the most recently created variable with that name (at any level). Common LISP uses lexical scoping for formal parameters of a function. 12

Static vs. Dynamic (cont.) Example: >(defun f (x y) (+ x (g y))) >(defun g (y) (* 10 x)) By static scoping: > (f 2 3) Error! X has no value in G! By dynamic scoping: > (f 2 3) 22 Static scoping is used in Common LISP. 13

Saving function in files Save your function definitions in files Load into LISP using load Examples: (load test.lsp) (load mylisp/test.lsp) (load c:\\lispcode\\first.l ) 14

LOGIC AS FUNCTIONS 15

True and False The constant nil indicates false The constant t indicates true Any non nil value is actually true as well Some built in predicates, such as not, and, or,... 16

Some built in predicates (atom arg) returns T if arg is an atom (NIL otherwise) (null arg) returns T if arg is nil (note: not and null have the same behaviour) (listp arg) returns T if arg is a list (symbolp arg) returns T if arg is a symbol (numberp arg) returns T if arg is a number (integerp arg) returns T if arg is an integer (typep arg type) returns T if arg is of type type type can be number, atom, symbol, list, null,... (equal arg1 arg2) returns T if the two arguments look alike 17

Examples > (setq x 5) 5 > (atom x) T > (atom x) T > (atom 5) T > (atom (1 2 3)) NIL > (listp (1 2 3)) T > (listp x) NIL > (numberp x) T > (numberp x) NIL > (symbolp x) NIL > (symbolp x) T > (typep x number) NIL > (typep x number) T > (typep x symbol) T > (atom nil) T > (listp nil) T > (numberp nil) NIL > (symbolp nil) T > (null nil) T 18

Built in predicates for arithmetic (zerop arg) returns T if arg is zero (oddp arg) returns T if arg is an odd number (evenp arg) returns T if arg is an even number (> arg1 arg2) returns T if arg1 is greater than arg2 (<, >=, <= are also defined) (= arg1 arg2) returns T if arguments are equal numbers 19

Conditionals: cond cond is similar to if... then Example: If x is a list, return its head (cond ( (listp x) (car x)) ) Example: If x is a list, return its head, otherwise return x itself. (cond ( (lisp x) (car x) ) ( T x ) ) T acts like otherwise Two cond clauses in this example. If the test in one cond clause is true, the rest of clause is evaluated and all other cond clauses are ignored. 20

Conditionals: cond General form: (cond (test1 exp11 exp12 exp 13...) (test2 exp21 exp12 exp 13...). (testn expn1 exp12 exp 13...) ) Each of the above list of expressions (1 to n) is called a cond clause. Each cond clause can have one to as many expressions. The first expression in each cond clause is the test. The cond clauses will be examined in the order. If the test of a cond clause evaluates to false, the rest of expressions in that cond clause will be ignored and the next cond clause will be examined. If the test evaluates to true, the rest of the expressions in the cond clause will be evaluated. The value returned by the last expression is returned as the value of cond. All remaining cond clauses will be ignored. If none of the tests evaluates to true, cond will evaluate to nil. 21

Example (defun mymin (x y z) (cond ( (not (and (numberp x) (numberp y) (numberp z))) nil) ( (and (<= x y) (<= x z)) x) ( (and (<= y x) (<= y z)) y) ( T z))) It accepts 3 arguments. If all arguments are numbers, it returns the minimum. Otherwise it will return nil. 22

Example (defun nilzero (x) (cond ((null x)) ((and (numberp x)(zerop x))) )) If the given argument is nil or zero, it will return T, otherwise nil. Both cond clauses have only one expression (only the test). If the test is true, its value true (T) will be returned. If none of them evaluates to true, nil will be returned. In the second cond clause, we cannot use zerop without numberp. Why? 23

Other conditionals If These two expressions perform the same function, (Add e to list lst if it is not already a member of lst) (member is a pre defined function in Common LISP) (if (member e lst) lst (cons e lst)) = (cond ((member e lst) lst) (t (cons e lst))) If evaluates its first argument, if true, evaluates and returns the second argument. Otherwise evaluates and returns the third argument (if present). Others such as when, unless, case 24