CSCI337 Organisation of Programming Languages LISP

Size: px
Start display at page:

Download "CSCI337 Organisation of Programming Languages LISP"

Transcription

1 Organisation of Programming Languages LISP

2 Getting Started Starting Common Lisp $ clisp i i i i i i i ooooo o ooooooo ooooo ooooo I I I I I I I o 8 8 I \ `+' / I \ `-+-' / ooooo 8oooo `- -' o 8 8 o ooooo 8oooooo ooo8ooo ooooo 8 Copyright (c) Bruno Haible, Michael Stoll 1992, 1993 Copyright (c) Bruno Haible, Marcus Daniels Copyright (c) Bruno Haible, Pierpaolo Bernardi, Sam Steingold 1998 Copyright (c) Bruno Haible, Sam Steingold Copyright (c) Sam Steingold, Bruno Haible [1]>

3 A Few CLISP Commands Lisp tries to evaluate anything you type into it. Constants: [1]> 1 1 [2]> [3]> "one" "one"

4 Lisp Functions Functions are written with parentheses: [1]> (+ 1 2) 3 [2]> (- 1 2) -1 [3]> (* 1 2) 2 [4]> (/ 1 2) 1/2 [5]> (* 2 3 4) 24

5 Combining Functions We can combine LISP functions thus: [1]> (+ (* 2 3) 5) 11 evaluates the expression (2*3)+5 and [2]> (* 2 (+ 3 5)) 16 evaluates the expression 2*(3+5)

6 Stopping Evaluation We can use the quote character to stop LISP from evaluating an expression. Compare: [1]> (+ 1 2) 3 with [2]> '(+ 1 2) (+ 1 2) and [3]> "(+ 1 2)" "(+ 1 2)"

7 Another Form of Quote We can write a quoted expression in two equivalent ways. We can write either: [1]> '(+ 1 2) or (+ 1 2) [2]> (quote (+ 1 2)) (+ 1 2)

8 Evaluating Quoted Expressions The function eval can force evaluation of an expression: [1]> (eval 3) 3 [2]> (eval (+ 2 3)) 5 [3]> (eval '(+ 2 3)) 5 [4]> (eval "(+ 2 3)") "(+ 2 3)"

9 Types in LISP Every expression in LISP has a type. We have seen some of these types already: Integer Ratio 1/2-3/4 Float String "a b c"

10 Hierarchy of Types in LISP Types in LISP form a heirarchy t [top level type (all other types are a sub-type)] sequence list array vector string number float rational integer ratio complex character symbol structure function hash-table nil

11 Booleans in LISP Note that LISP does not have an explicit Boolean data type. Instead it has two constants: T or t (equivalent to logical true) and NIL or nil (equivalent to logical false) T is the most general type. NIL is the least general type the empty set.

12 Testing Types We can test what the type of an expression is in LISP by using the typep function: [1]> (typep 5 'integer) T [2]> (typep 5 'float) NIL [3]> (typep 2 'rational) T [4]> (typep 2/3 'rational) T [5]> (typep 2/3 'ratio) T [6]> (typep 2 'ratio) NIL

13 Testing Types We can also use a shorthand version of typep: [1]> (integerp 5) T [2]> (floatp 5) NIL [3]> (rationalp 2) T [4]> (rationalp 2/3) T

14 Testing Types Not all types work, however. [5]> (ratiop 2/3) ** - Continuable Error EVAL: undefined function RATIOP... There is no function ratiop. This can be remedied as we will see later.

15 LISTS Lists are one of the critical LISP data types. We represent a list as a sequence of elements contained in parentheses. Thus: [1]> '(1 2 3) (1 2 3) is a list with three elements. Note: so is (+ 2 3)

16 LISTS We can demonstrate this as follows: [1]> (typep '(1 2 3) 'list) or T [2]> (listp '(+ 2 3)) T

17 Manipulating LISTS A list consists of two parts: A head accessible via the car function: [1]> (car '(1 2 3)) 1 A tail accessible via the cdr function: [2]> (cdr '(1 2 3)) (2 3)

18 Manipulating LISTS We can combine car and cdr to extract elements from a list. Thus: [1]> (car (cdr '(1 2 3))) 2 extracts the second element. We can combine sequences of car and cdr into a single function: [2]> (cadr '(1 2 3)) 2

19 Lists of Lists A List can contain a list as an element. Thus: [1]> '(1 (2 3) (4 5)) (1 (2 3) (4 5)) is a list of three elements: an integer, [2]> (car '(1 (2 3) (4 5))) 1 a list, [3]> (cadr '(1 (2 3) (4 5))) (2 3) and another list, [4]> (caddr '(1 (2 3) (4 5))) (4 5)

20 Testing for Equality We can test the equality of two expressions with the equal function. Thus: [1]> (equal 3 3) T [2]> (equal 3 4) NIL [3]> (equal (+ 2 4) (* 2 3)) T

21 Testing for Equality As we would expect: [1]> (equal 3 (+ 1 2)) T and [2]> (equal '3 (+ 1 2)) T but [3]> (equal 3 '(+ 1 2)) NIL

22 Equality of Lists As you might expect: [1]> (equal '( ) '((1 2) (3 4))) NIL The first is a list of 4 atoms, the second a list of two lists.

23 Complex Lists A list can contain multiple data types. Thus: [1]> '((1 "fred") (2 "bill") (3 "jane")) ((1 "fred") (2 "bill") (3 "jane")) is a list of lists where each sub-list contains an integer and a string.

24 Building Lists There are a number of functions for building lists. These include: list cons append as well as simply quoting the list Each works in a different way.

25 The list Function This function builds a list from a sequence of elements. Thus: [1]> (list 1 2 3) (1 2 3) and [2]> (list (list 1 2) (list 2 3)) ((1 2) (2 3))

26 The list Function This function is equivalent to quoting the list. Thus: [1]> (list 1 2 3) (1 2 3) and [1]> '(1 2 3) (1 2 3) are equivalent.

27 The cons Function This function adds an element to the head of a list. Thus: [1]> (cons 1 (list 2 3)) or (1 2 3) [2]> (cons 1 '(2 3)) (1 2 3)

28 The append Function This function adds the contents of two lists together to form a single list. Thus: [1]> (append (list 1 2) (list 3 4)) or ( ) [2]> (append '(1 2) '(3 4)) ( )

29 More About the cons Function As we would expect: [1]> (cons 1 '(2)) (1 2) However: [2]> (cons 1 2) (1. 2) What is going on here? Where did the dot come from?

30 How Lists Are Built A list is built as a sequence of words. The first half of each word contains the head of the list. The second half contains a pointer to the tail of the list. The last word contains the last element of the list and NIL.

31 How Lists Are Built Graphically: The list (1 2 3) is built as follows nil We can also write this as follows: (1. (2. (3. NIL)))

32 How Lists Are Built Thus the list: (1 2) is really shorthand for: (1. (2. nil)) 1 2 nil Which is clearly different from: (1. 2) 1 2

33 How Lists Are Built We can verify this as follows: [1]> '(1. nil) and (1) [2]> '(1. (2. (3. nil))) (1 2 3)

34 Accessing Lists Elements The function nth extracts the n th element of a list. Thus: [1]> (nth 0 '(1 (2 3) (4 5))) 1 [2]> (nth 1 '(1 (2 3) (4 5))) (2 3) [3]> (nth 2 '(1 (2 3) (4 5))) (4 5) [4]> (nth 1 (nth 2 '(1 (2 3) (4 5)))) 5

35 Vectors Lists are easy to use but inefficient. We can only get to a list element by following chains of pointers. An alternative to a list is a vector, a directly indexed sequence of values. A vector in LISP can be a sequence of any data type.

36 Making Vectors We can construct a vector using the vector function. Thus: [1]> (vector 1 2 3) #(1 2 3) Note the notation for a vector. We can also create a vector in this way: [2]> #(1 2 3) #(1 2 3)

37 Complicated Vectors A vector can contain multiple data types. For example: [1]> (vector 1 '(2 3) #(2 3) 2/3) #(1 (2 3) #(2 3) 2/3) is a vector containing: An integer 1 A list (2 3) A vector #(2 3) A ratio 2/3

38 Vectors vs. Lists A vector is not a list. Consider: [1]> (listp '(1 2 3)) T Compared with: [2]> (listp #(1 2 3)) NIL This means we cannot use car, cdr and nth with vectors.

39 Vectors vs. Lists Both vectors and lists are sequences however. Consider: [1]> (typep '(1 2 3) 'sequence) T [2]> (typep #(1 2 3) 'sequence) T

40 Arrays An array is a generalisation of a vector to more than one dimension. We construct an array thus: [1]> #2a((1 2 3)(4 5 6)) or #2A((1 2 3) (4 5 6)) [2]> #2a((1 2)(3 4)(5 6)) #2A((1 2) (3 4) (5 6)) Note the number of dimensions.

41 Vectors are Arrays A vector is a 1-dimensioned array: [3]> #1a(1 2 3) #(1 2 3) Note: an array is not a vector of vectors. [1]> (equal #2a((1 2)(2 3)) #(#(1 2)#(2 3))) NIL

42 Accessing Array Elements We can access an array element with the aref function: [1]> (aref #(1 2 3) 1) 2 [2]> (aref #2a((1 2 3)(4 5 6)) 1 0) 4

43 Strings Any LISP program is likely to involve character strings. In LISP, a string is a sub-type of vector. Specifically a vector of characters. String are specified with double quotes. [1]> "This is a string." "This is a string."

44 Combining Strings Strings can be joined with the concatenate function. Thus: [1]> (concatenate 'string "This is " "a string.") "This is a string. and [2]> (concatenate 'string "This " "is" " another " "string.") "This is another string."

45 Searching Strings We can look for a substring using the search function. Thus: [1]> (search "c" "abcde") or 2 [2]> (search "xyz" "abcde") NIL

46 Extracting Substrings We can use the subseq function to extract a substring from a string. The function has two forms: [1]> (subseq "This is a string" 8) and "a string (extract from character 8 onwards) [2]> (subseq "this is a string" 5 7) "is" (extract from character 5, stop at character 7)

47 Extracting Characters The char function can be used to extract a single character from a string: [1]> (char "this is a string" 3) #\s [2]> (char "this is a string" 4) #\Space

48 The Character Type The sequence "x" refers to a string of length one. This is not the same as a single character. We can specify a single character in LISP as follows: [1]> #\a #\a [2]> #\space #\Space Note that we use the keyword space to refer to a space character.

49 Trimming Strings The string-trim function can be used to remove unwanted characters (often space) from the ends of a string. [3]> (string-trim '(#\space) " this string needs trimming ") or "this string needs trimming" [4]> (string-trim '(#\a #\z) "azaabbbzzbbbzaza") "bbbzzbbb Note that interior characters are not removed.

50 String Case Two functions allow the manipulation of the case of letters in strings: [8]> (string-upcase "This is a string!") "THIS IS A STRING! and [9]> (string-downcase "SO is THIS!") "so is this!"

51 More on equality LISP distinguishes between four different equality tests: eq eql equal and equalp Each behaves in a slightly different way.

52 The eq Function (eq x y) is true if and only if x and y are the same identical object. Effectively this means that x and y point at the same memory location. The result of the eq function is often not what you expect: [1]> (eq "abc" "abc") NIL

53 The eql Function (eql x y) is true if (eq x y) is true, or if x and y are numbers of the same type with the same value, or if they are character objects that represent the same character. [1]> (eql "abc" "abc") NIL Both eq and eql have implementation-dependent results for some tests. The eql function has slightly less implementationdependence. (eq 3 3) vs. (eql 3 3)

54 The equal Function (equal x y) is true if x and y are structurally similar (isomorphic) objects. A rough rule of thumb is that two objects are equal if and only if their printed representations are the same. [1]> (equal "abc" "abc") T

55 The equalp Function (equalp x y) if (equal x y); if x and y are characters and satisfy char-equal, which ignores alphabetic case and certain other attributes of characters; if they are numbers and have the same numerical value, even if they are of different types; or if they have components that are all equalp. [4]> (equalp Abc" "abc") T

56 LISP Functions LISP supports two types of functions: unnamed (lambda) functions and named functions. We will look at these in turn.

57 Lambda Functions Lisp allows us to define an anonymous function using the lambda form. This looks like: (lambda (parameter_list) (function_body)) where (parameter_list) is the list of formal parameters for the function and (function_body) is the code of the function.

58 Lambda Functions E.g. [1]> '(lambda (x) (* 2 x)) (LAMBDA (X) (* 2 X)) which can be compared with λx. 2x

59 Evaluating Lambda Functions Because they are equivalent to any other LISP functions, lambda functions are evaluated in the same way. Thus: [2]> ((lambda (x) (* 2 x)) 4) 8 is equivalent to ((λx. 2x) 4)

60 Multivariate Lambda Functions We can define a function of more than one variable as follows: [1]> '(lambda (x y) (+ (* x y) y)) (LAMBDA (X Y) (+ (* X Y) Y)) and evaluate it thus: [2]> ((lambda (x y) (+ (* x y) y)) 2 3) 9

61 More Complex Lambda Functions Let us construct a lambda function to evaluate the roots of the quadratic equation: ax 2 + bx + c = 0 using the formula: x = (-b ± (b 2-4ac))/2a Thus: [1]> '(lambda (a b c) (list (/ (+ (- b) (sqrt (- (* b b) (* 4 a c)))) (* 2 a)) (/ (- (- b) (sqrt (- (* b b) (* 4 a c)))) (* 2 a))) ) (LAMBDA (A B C) (LIST (/ (+ (- B) (SQRT (- (* B B) (* 4 A C)))) (* 2 A)) (/ (- (- B) (SQRT (- (* B B) (* 4 A C)))) (* 2 A))))

62 More Complex Lambda Functions We can use this function to solve the equation: x 2 x 6 = 0 as follows: [1]> ((lambda (a b c) (list (/ (+ (- b) (sqrt (- (* b b) (* 4 a c)))) (* 2 a)) (/ (- (- b) (sqrt (- (* b b) (* 4 a c)))) (* 2 a)))) ) (3-2) giving the results: x = 3, x = -2

63 Named Functions While the lambda form of a function is useful for single evaluations, it is not ideal where we need to use the same function repeatedly. For this purpose we need to be able to construct a named function: [1]> (defun quad (a b c) (list (/ (+ (- b) (sqrt (- (* b b) (* 4 a c)))) (* 2 a)) (/ (- (- b) (sqrt (- (* b b) (* 4 a c)))) (* 2 a)))) QUAD Note: we simply replace lambda with defun name.

64 Using Named Functions Once we have defined the function quad we can use it like any other LISP function: [2]> (quad 1 0-4) and (2-2) [3]> (quad ) ( )

65 The if Function In LISP, a choice between two alternatives is made with the if construct. Its form is: (if Boolean-expression true-expression false-expression) Thus: [5]> (if (equal 2 2) 1 2) 1 and [6]> (if (equal 2 3) 1 2) 2

66 The if Function We can use if to refine the quad function: [1]> (defun quad (a b c) (if (< (* b b) (* 4 a c)) "Error: no real solutions" (list (/ (+ (- b) (sqrt (- (* b b) (* 4 a c)))) (* 2 a)) (/ (- (- b) (sqrt (- (* b b) (* 4 a c)))) (* 2 a)) ))) QUAD to avoid errors with complex roots.

67 The if Function We can now use our new version of the quad function: [2]> (quad ) ( ) [3]> (quad 1 2-6) ( ) [4]> (quad 1 2 6) "Error: no real solutions"

68 Recursion LISP allows the definition of recursive functions. E.g the factorial function can be defined as: [1]> (defun fact (x) (if (equal x 1) 1 (* x (fact (- x 1))))) FACT and used: [2]> (fact 5) 120

69 Output As we have already seen we get the value of an expression as output from LISP. This is not always what we want. Consider the following function to count from i to j: [1]> (defun count (x y) (if (> x y) nil (count (+ x 1) y))) COUNT [2]> (count 1 5) NIL This is probably not what we wanted.

70 Output We need a way to see the count proceeding. Consider: [1]> (defun count (x y) (if (> x y) nil (count (+ (print x) 1) y))) COUNT [2]> (count 1 5) NIL The print function does the job nicely.

71 Variations of the print Function. There are a few versions of print that produce slightly different output: [1]> (print "abc") "abc" "abc" [2]> (prin1 "abc") "abc" "abc" [3]> (princ "abc") abc "abc"

72 Editing, Loading and Compiling LISP Let us create a file called quad.lisp containing the following code: (defun quad (a b c) (if (< (* b b) (* 4 a c)) "Error: no real solutions" (list (/ (+ (- b) (sqrt (- (* b b) (* 4 a c)))) (* 2 a)) (/ (- (- b) (sqrt (- (* b b) (* 4 a c)))) (* 2 a)) )))

73 Editing, Loading and Compiling LISP We can the start LISP and load this code: [1]> (load "quad.lisp") ;; Loading file quad.lisp... ;; Loaded file quad.lisp T We can now use the quad function defined in the file: [2]> (quad 1-3 2) (2 1) [3]> (quad 1 1 2) "Error: no real solutions"

74 Editing, Loading and Compiling LISP We can now compile the file: [1]> (compile-file "quad.lisp") Compiling file /home/ian/quad.lisp... Wrote file /home/ian/quad.fas 0 errors, 0 warnings #P"/home/ian/quad.fas" ; NIL ; NIL

75 Editing, Loading and Compiling LISP Now we can load and use the compiled version of the program: [1]> (load "quad.fas") ;; Loading file quad.fas... ;; Loaded file quad.fas T [2]> (quad 1-3 4) "Error: no real solutions" [3]> (quad 1-3 2) (2 1)

76 Input in LISP The LISP read function reads one LISP object (a number, list, string etc.) and returns the object as its value. E.g. Number: [1]> (read) 3 3 Note the entry does not need to be quoted.

77 Input in LISP String: [2]> (read) "ab cd ef" List: "ab cd ef" [3]> (read) (1 2 (3 4)) (1 2 (3 4))

78 Input in LISP We can also input a string using the LISP read-line function: [11]> (read-line) abc def "abc def" ; NIL The value of (read-line) is the string entered.

79 An Alternative to the if Function. LISP supports a more general conditional function than if. This is the cond function. Its syntax is: (cond (condition_1 expression_1) (condition_2 expression_2) (condition_n expression_n) ) where each condition is a Boolean expression and each expression is an associated function.

80 An Alternative to the if Function. The cond function works in a similar fashion to the case or switch statements of imperative languages. We can implement if as a two-way cond: (if x a b) is equivalent to: (cond (x a) (T b)) Traditionally, LISP programmers always used cond rather than if.

81 An Example LISP Program - primes The following slides will examine the construction of a LISP function primes which will: take no arguments; read an integer upper bound and return an ordered list of primes less than or equal to the input bound. We will build the function bottom-up.

82 An Example LISP Program - primes We first need a Boolean function to decide whether one number is divisible by a second: (defun test-div (x y) (integerp (/ x y))) We can test this function: [1]> (test-div 4 2) T [2]> (test-div 17 5) NIL We are OK so far

83 An Example LISP Program - primes We can use this to build a function to determine whether a candidate is a prime number by repeated test divisions: (defun test-prime (cand div) (cond ((= cand div) t) ((test-div cand div) nil) (t (test-prime cand (+ div 2))))) Here cand is the possible prime and div is the next trial divisor. Note the recursive call of test-prime.

84 An Example LISP Program - primes Again, we can test this function: [1]> (test-prime 23 3) T [2]> (test-prime 25 3) NIL Once more, this seems fine

85 An Example LISP Program - primes Next we need a utility function, is-prime, to kickstart the test-prime function: (defun is-prime (cand) (test-prime cand 3)) We can test this: [1]> (is-prime 19) T [2]> (is-prime 21) NIL Still looking good

86 An Example LISP Program - primes Now we need a function which, given a (possibly prime) candidate, returns the next prime: (defun next-prime (cand) (cond ((is-prime cand) cand) (t (next-prime (+ cand 2))))) We could have used if here instead of cond. This is our second recursive function.

87 An Example LISP Program - primes Testing the next-prime function: [1]> (next-prime 19) 19 [2]> (next-prime 21) 23 Still on track

88 An Example LISP Program - primes We now need a function that will add to a list of prime numbers until we reach an upper bound: (defun list-primes (limit list) (cond ((> (next-prime (+ (car list) 2)) limit) list) (t (list-primes limit (cons (next-prime (+ (car list) 2)) list))))) Note that this function expects as input the upper bound (limit) and a partial list of primes (list). We will need to prime the list-primes function with a list like (3 2) because we need the first odd prime and because the list is constructed in reverse order.

89 An Example LISP Program - primes Testing this function: [12]> (list-primes 20 '(3 2)) ( ) We are nearly there

90 An Example LISP Program - primes Finally, we can write the primes function: (defun primes () (reverse (list-primes (read) '(3 2)))) Which we can test: [13]> (primes) 40 ( ) And we are done.

91 An Example LISP Program - primes Notes: this is not the most efficient way to calculate the prime numbers; it has a less than elegant starting point; It has a load of external functions we really shouldn t be able to see. However, it does illustrate the usual method of program development in LISP: start at the bottom; build up gradually; test as you go.

92 Sequential Code LISP allows the evaluation of a sequence of functions. The value of the sequence is the value of the last evaluated expression. This is not generally useful unless we introduce variables. However, there is one case in which this can be used without them.

93 The prompt Function Let us define a function, prompt, which solicits and reads an input: (defun prompt (x) (print x) (read)) The body of the prompt function is the sequence of functions: (print x) and (read)

94 Revisiting primes We can use prompt to pretty up the primes function: (defun primes () (reverse (list-primes (prompt "Enter the upper limit for primes:") '(3 2)))) Which we run: [14]> (primes) "Enter the upper limit for primes:" 40 ( )

95 Revisiting primes We could improve primes by (among other things): replacing the list with an array; creating the array in order; testing divisibility only against the primes we have already found; stopping the test earlier. Some of these changes would be trivial to code. Others would be almost impossible at least impossible without variables.

96 Variables in LISP We can always write a LISP program without the use of variables other than formal parameters of functions. However, this can lead to significant inefficiency. Consider the list-primes function: the expression (car list) appears twice. This is a minor example of what can be a major problem.

97 Variables in LISP Consider the following pseudo code: (defun func (x) (cond ((< 0 (expr0)) (expr1)) ((= 0 (expr0)) (expr2)) ((> 0 (expr0)) (expr3)))) where each of the tests involves a complex common expression, expr0. In the worst case we would evaluate the common expression three times.

98 Variables in LISP Compare that with the following: (defun func (x) (let ((v (expr0))) (cond ((< 0 v) (expr1)) ((= 0 v) (expr2)) ((> 0 v) (expr3))))) By pre-evaluating expr0 and saving the result in a variable v we have saved the repeated evaluation of the expression.

99 Variables in LISP The syntax of let is as follows: (let (list-of-associations) code-using-associations) where: list-of-associations is a list of pairs of the form: (name value) and code-using-associations is a sequence of one or more expressions using the names.

100 Variables in LISP A simple example: [1]> (defun f (x) (let ((a 1) (b 2) (c 3)) (+ (* a x x) (* b x) c))) F evaluates ax 2 + bx + c for (a = 1, b = 2, c = 3) [2]> (f 5) 38 Note that a, b and c are local to the let function.

101 Variables in LISP Compare this with: [1]> (let ((a 1)(b 2)(c 3)) (defun f (x) (+ (* a x x)(* b x) c))) F What has changed? [2]> (f 5) 38 Why does this still work?

102 Variables in LISP How about: [3]> (let ((a 2)(b 3)(c 4)) (f 5)) 38 Why isn t the answer 69? Note that: [4]> a *** - EVAL: variable A has no value etc. a is, as expected, undefined.

103 Scope of Variables The behaviour seen on the last slide is due to the scoping and evaluation time of variables in LISP. Thus, although a, b and c are undefined the values associated with them at the time f was defined are locked in.

104 Global Variables As we have seen, variables defined with let are local. We can define global variables using the setf function. E.g. [1]> (setf a 1) 1 [2]> a 1

105 Local and Global Together Care must be taken to ensure that the variable used is the right one. Consider: [1]> (setf a 'one) ONE [2]> (defun test (a) a) TEST [3]> (test 'two) TWO [4]> a ONE

106 Local and Global Together We can access the global version of a variable with the symbol-value function: [5]> (defun test (a) (list a (symbol-value 'a))) TEST [6]> (test 'three) (THREE ONE)

107 More Scope Issues Consider: [1]> (setf a 1) 1 [2]> (defun f () a) F [3]> (let ((a 5)) (f)) 1 Confused yet? By default, CLISP used lexical scope.

108 Lexical Scope With lexical scope, a variable within a function is bound at function definition time. Thus: (defun f () a) binds the free variable a to the global symbol (even if one does not yet exist). While: (let ((a 5)) (defun f () a)) binds the free variable a to the local variable (or its value).

109 Dynamic Scope We can force a variable to have dynamic scope with the defvar function. Consider the following sequence: [1]> (defvar a) A [2]> (setf a 1) 1 [3]> (defun f () a) F [4]> (let ((a 2)) (f)) 2 [5]> (f) 1

110 Closures Because Common Lisp is lexically scoped, when we define a function containing free variables, the system must save copies of the bindings of those variables at the time the function was defined. Such a combination of a function and a set of variable bindings is called a closure. We will come back to closures in a moment.

111 More on Functions A language which allows functions as data objects must also provide some way of calling them. In Lisp, this function is apply. Generally, we call apply with two arguments: a function and a list of arguments for it.

112 More on Functions The following four expressions all have the same effect: (+ 1 2) (apply # + (1 2)) (apply (symbol-function +) (1 2)) (apply # (lambda (x y) (+ x y)) (1 2)) We can avoid specifying the function arguments as a list (as in the second example) by using the funcall function. (funcall # + 1 2)

113 The # Operator The # operator quotes a function in a similar way to the operator quoting a symbol. Thus, in the same way we can set a variable to a list: (setf a (1 2)) we can set a variable to a function: (setf b # cons)

114 The # Operator, funcall and apply If we set a variable to a function: [1]> (setf a #'cons) #<SYSTEM-FUNCTION CONS> We can invoke it with funcall: [2]> (funcall a 1 2) (1. 2) We can also invoke it with apply: [3]> (apply a '(1 2)) (1. 2)

115 Direct Call with # We cannot use it directly, however: [4]> (a '(2 3)) ** - Continuable Error EVAL: undefined function A... The reason for the error in the last example is that, although a evaluates to a function, a is not the name of any defined function.

116 Functions That Make Functions Suppose we want a set of similar functions: addone addtwo addthree We could do this by direct definition: (defun addone (x) (+ x 1)) (defun addtwo (x) (+ x 2)) (defun addthree (x) (+ x 3))

117 Functions That Make Functions An alternative approach is to define a generic function: (defun addsome (n) # (lambda (x) (+ n x))) We can then define functions with setf: (setf addone (addsome 1)) (setf addtwo (addsome 2)) (setf addthree (addsome 3)) which can be accessed with funcall. So what?

118 List Functions Let us define a function to square a number: [1]> (defun square (x) (* x x)) SQUARE We can use it to square a single number but not a list of numbers. We can apply the function to each element of a list using the mapcar function: [2]> (mapcar #'square '( )) ( )

119 List Functions We could also combine mapcar and lambda to create list functions: [3]> (defun listtimes (lst n) (mapcar #'(lambda (x) (* x n)) lst)) LISTTIMES Which can be called: [4]> (listtimes '( ) 3) ( )

120 List Functions Another list (applicative) function is find-if. Given a Boolean predicate and a list, find-if returns the first list element that satisfies the Boolean predicate: [1]> (find-if #'integerp '(a b c 1 2 3)) 1 [2]> (find-if #'(lambda (x) (> x 3)) '( )) 4

121 List Functions We can also use find-if with our own named functions: [1]> (find-if #'is-prime '( )) 23

122 More Applicative Functions The function remove-if eliminates values from a list that satisfy a Boolean predicate: [1]> (remove-if #'evenp '( )) ( ) Similar is the remove-if-not function: [2]> (remove-if-not #'evenp '( )) ( )

123 More Applicative Functions Some applicative functions are not list-valued. One such function is reduce. The first argument to reduce must be a function that takes two arguments. The reduce function progressively applies this bivariate function to the list: [3]> (reduce #'+ '( )) 15

124 More Applicative Functions Another applicative function is every. This returns T if every element of the list satisfies the predicate: [5]> (every #'numberp '( )) T [6]> (every #'numberp '(O )) NIL That second zero was really an oh.

125 More on mapcar If we specify a bivariate function to mapcar, we can use it to operate on two lists in synchronisation: [7]> (mapcar #'* '( ) '( )) ( )

126 Local Functions Remember one of our objections to the primes solution? We have a load of external functions that we really should not be able to call. Nesting defun s does not solve this problem. Any function defined by defun is global. There is a way to make functions local. Use labels in place of defun.

127 Local Functions As an example: [1]> (defun count-up (n) (labels ((r-count-up (cnt) (if (> cnt n) nil (cons cnt (r-count-up (+ cnt 1)))))) (r-count-up 1))) count-up [2]> (count-up 5) ( ) The r-count-up function is only defined within count-up.

128 The labels Function The form of the labels function is: (labels ((fn-1 args-1 body-1)... (fn-n args-2 body-2)) body) where we define a series of named local functions fn-1 to fn-n which can be called within the function defined in body. The local functions can also call each other. They can also reference their parent s variables.

129 Some More I/O The format function allows the output of formatted output. The form of the function is: (format t "format-string" value-1... value-n) The format-string is a literal string which may include special character sequences. These escape sequences are preceded with the ~ character.

130 Escape Sequences for format Among the escape sequences for format are: ~% start a new line; ~& start a new line if not at start of line; ~s insert a value here; ~a insert a value without escape characters

131 Using format The following is an example of format in use: [1]> (defun test (x) (format t "~%With escapes: ~s" x) (format t "~&No escapes: ~a" x)) TEST [2]> (test "Hello World!") With escapes: "Hello World!" No escapes: Hello World! NIL Note that format evaluates to NIL.

132 The y-or-n-p function. You can ask a yes/no question with the y-or-n-p function: [1]> (defun riddle () (if (y-or-n-p "Do you know the nature of Zen?") (format t "Then do not ask!") (format t "You have found it!"))) RIDDLE [2]> (riddle) Do you know the nature of Zen? (y/n) yes Then do not ask! NIL [3]> (riddle) Do you know the nature of Zen? (y/n) N You have found it! NIL

133 Primes Again Here is a revised version of the primes program: (defun primes () ( labels ( (test-prime (cand div) (cond ((= cand div) t) (((lambda (x y) (integerp (/ x y))) cand div) nil) (t (test-prime cand (+ div 2))))) (next-prime (cand) (cond (((lambda (cand) (test-prime cand 3)) cand) cand) (t (next-prime (+ cand 2))))) (list-primes (limit l) (cond ((> (next-prime (+ (car l) 2)) limit) l) (t (list-primes limit (cons (next-prime (+ (car l) 2)) l)))))) (reverse (list-primes ((lambda (x) (print x) (read)) "Enter the upper limit for primes:") '(3 2)))))

Common Lisp. Blake McBride

Common Lisp. Blake McBride Contents Common Lisp Blake McBride (blake@mcbride.name) 1 Data Types 2 2 Numeric Hierarchy 3 3 Comments 3 4 List Operations 4 5 Evaluation and Quotes 5 6 String Operations 5 7 Predicates 6 8 Math Predicates

More information

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

CS 480. Lisp J. Kosecka George Mason University. Lisp Slides CS 480 Lisp J. Kosecka George Mason University Lisp Slides Symbolic Programming Symbols: +, -, 1, 2 etc. Symbolic expressions: (+ 1 2), (+ (* 3 4) 2) Symbolic programs are programs that manipulate symbolic

More information

Common LISP Tutorial 1 (Basic)

Common LISP Tutorial 1 (Basic) Common LISP Tutorial 1 (Basic) CLISP Download https://sourceforge.net/projects/clisp/ IPPL Course Materials (UST sir only) Download https://silp.iiita.ac.in/wordpress/?page_id=494 Introduction Lisp (1958)

More information

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

Symbolic Programming. Dr. Zoran Duric () Symbolic Programming 1/ 89 August 28, / 89 Symbolic Programming Symbols: +, -, 1, 2 etc. Symbolic expressions: (+ 1 2), (+ (* 3 4) 2) Symbolic programs are programs that manipulate symbolic expressions. Symbolic manipulation: you do it all the

More information

Lisp. Versions of LISP

Lisp. Versions of LISP Lisp Versions of LISP Lisp is an old language with many variants Lisp is alive and well today Most modern versions are based on Common Lisp LispWorks is based on Common Lisp Scheme is one of the major

More information

Functional programming with Common Lisp

Functional programming with Common Lisp Functional programming with Common Lisp Dr. C. Constantinides Department of Computer Science and Software Engineering Concordia University Montreal, Canada August 11, 2016 1 / 81 Expressions and functions

More information

Functional Programming. Pure Functional Languages

Functional Programming. Pure Functional Languages Functional Programming Pure functional PLs S-expressions cons, car, cdr Defining functions read-eval-print loop of Lisp interpreter Examples of recursive functions Shallow, deep Equality testing 1 Pure

More information

Lecture Notes on Lisp A Brief Introduction

Lecture Notes on Lisp A Brief Introduction Why Lisp? Lecture Notes on Lisp A Brief Introduction Because it s the most widely used AI programming language Because Prof Peng likes using it Because it s good for writing production software (Graham

More information

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

INF4820: Algorithms for Artificial Intelligence and Natural Language Processing. Common Lisp Fundamentals INF4820: Algorithms for Artificial Intelligence and Natural Language Processing Common Lisp Fundamentals Stephan Oepen & Murhaf Fares Language Technology Group (LTG) August 30, 2017 Last Week: What is

More information

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

Announcement. Overview. LISP: A Quick Overview. Outline of Writing and Running Lisp. Overview Announcement Announcement Lisp Basics CMUCL to be available on sun.cs. You may use GNU Common List (GCL http://www.gnu.org/software/gcl/ which is available on most Linux platforms. There is also

More information

Functional Programming. Pure Functional Languages

Functional Programming. Pure Functional Languages Functional Programming Pure functional PLs S-expressions cons, car, cdr Defining functions read-eval-print loop of Lisp interpreter Examples of recursive functions Shallow, deep Equality testing 1 Pure

More information

Functional Programming. Pure Functional Programming

Functional Programming. Pure Functional Programming Functional Programming Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends only on the values of its sub-expressions (if any).

More information

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

Scheme Tutorial. Introduction. The Structure of Scheme Programs. Syntax Scheme Tutorial Introduction Scheme is an imperative language with a functional core. The functional core is based on the lambda calculus. In this chapter only the functional core and some simple I/O is

More information

Imperative, OO and Functional Languages A C program is

Imperative, OO and Functional Languages A C program is Imperative, OO and Functional Languages A C program is a web of assignment statements, interconnected by control constructs which describe the time sequence in which they are to be executed. In Java programming,

More information

Common LISP-Introduction

Common LISP-Introduction Common LISP-Introduction 1. The primary data structure in LISP is called the s-expression (symbolic expression). There are two basic types of s-expressions: atoms and lists. 2. The LISP language is normally

More information

Scheme: Strings Scheme: I/O

Scheme: Strings Scheme: I/O Scheme: Strings Scheme: I/O CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Wednesday, April 5, 2017 Glenn G. Chappell Department of Computer Science University of

More information

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

CIS4/681 { Articial Intelligence 2 > (insert-sort '( )) ( ) 2 More Complicated Recursion So far everything we have dened requires 1 A couple of Functions 1 Let's take another example of a simple lisp function { one that does insertion sort. Let us assume that this sort function takes as input a list of numbers and sorts them in ascending

More information

Functions, Conditionals & Predicates

Functions, Conditionals & Predicates 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)

More information

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

11/6/17. Functional programming. FP Foundations, Scheme (2) LISP Data Types. LISP Data Types. LISP Data Types. Scheme. LISP: John McCarthy 1958 MIT Functional programming FP Foundations, Scheme (2 In Text: Chapter 15 LISP: John McCarthy 1958 MIT List Processing => Symbolic Manipulation First functional programming language Every version after the

More information

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

Scheme: Data. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, Glenn G. Scheme: Data CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, 2017 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks ggchappell@alaska.edu

More information

Scheme Quick Reference

Scheme Quick Reference Scheme Quick Reference COSC 18 Winter 2003 February 10, 2003 1 Introduction This document is a quick reference guide to common features of the Scheme language. It is by no means intended to be a complete

More information

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

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define CS 6A Scheme Summer 207 Discussion 0: July 25, 207 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015 SCHEME 7 COMPUTER SCIENCE 61A October 29, 2015 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

Lisp Basic Example Test Questions

Lisp Basic Example Test Questions 2009 November 30 Lisp Basic Example Test Questions 1. Assume the following forms have been typed into the interpreter and evaluated in the given sequence. ( defun a ( y ) ( reverse y ) ) ( setq a (1 2

More information

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

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives CS 6A Scheme Fall 208 Discussion 8: October 24, 208 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write

More information

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

Lambda Calculus and Lambda notation in Lisp II. Based on Prof. Gotshalks notes on Lambda Calculus and Chapter 9 in Wilensky. λ Calculus Basis Lambda Calculus and Lambda notation in Lisp II Based on Prof. Gotshalks notes on Lambda Calculus and Chapter 9 in Wilensky Mathematical theory for anonymous functions» functions that have

More information

Scheme Quick Reference

Scheme Quick Reference Scheme Quick Reference COSC 18 Fall 2003 This document is a quick reference guide to common features of the Scheme language. It is not intended to be a complete language reference, but it gives terse summaries

More information

FP Foundations, Scheme

FP Foundations, Scheme FP Foundations, Scheme In Text: Chapter 15 1 Functional Programming -- Prelude We have been discussing imperative languages C/C++, Java, Fortran, Pascal etc. are imperative languages Imperative languages

More information

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

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives CS 6A Scheme Fall 207 Discussion 7: October 25, 207 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write

More information

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

INF4820: Algorithms for Artificial Intelligence and Natural Language Processing. More Common Lisp INF4820: Algorithms for Artificial Intelligence and Natural Language Processing More Common Lisp Stephan Oepen & Murhaf Fares Language Technology Group (LTG) September 6, 2017 Agenda 2 Previously Common

More information

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

LISP. Everything in a computer is a string of binary digits, ones and zeros, which everyone calls bits. LISP Everything in a computer is a string of binary digits, ones and zeros, which everyone calls bits. From one perspective, sequences of bits can be interpreted as a code for ordinary decimal digits,

More information

CS 360 Programming Languages Interpreters

CS 360 Programming Languages Interpreters CS 360 Programming Languages Interpreters Implementing PLs Most of the course is learning fundamental concepts for using and understanding PLs. Syntax vs. semantics vs. idioms. Powerful constructs like

More information

Functional Programming

Functional Programming Functional Programming CS331 Chapter 14 Functional Programming Original functional language is LISP LISt Processing The list is the fundamental data structure Developed by John McCarthy in the 60 s Used

More information

Notes on Higher Order Programming in Scheme. by Alexander Stepanov

Notes on Higher Order Programming in Scheme. by Alexander Stepanov by Alexander Stepanov August 1986 INTRODUCTION Why Scheme? Because it allows us to deal with: 1. Data Abstraction - it allows us to implement ADT (abstact data types) in a very special way. The issue of

More information

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017 SCHEME 8 COMPUTER SCIENCE 61A March 2, 2017 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

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

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

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

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives CS 61A Scheme Spring 2018 Discussion 7: March 21, 2018 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme

More information

An Introduction to Scheme

An Introduction to Scheme An Introduction to Scheme Stéphane Ducasse stephane.ducasse@inria.fr http://stephane.ducasse.free.fr/ Stéphane Ducasse 1 Scheme Minimal Statically scoped Functional Imperative Stack manipulation Specification

More information

SCHEME The Scheme Interpreter. 2 Primitives COMPUTER SCIENCE 61A. October 29th, 2012

SCHEME The Scheme Interpreter. 2 Primitives COMPUTER SCIENCE 61A. October 29th, 2012 SCHEME COMPUTER SCIENCE 6A October 29th, 202 In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs, we will eventually

More information

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen COP4020 Programming Languages Functional Programming Prof. Robert van Engelen Overview What is functional programming? Historical origins of functional programming Functional programming today Concepts

More information

Introduction to Scheme

Introduction to Scheme How do you describe them Introduction to Scheme Gul Agha CS 421 Fall 2006 A language is described by specifying its syntax and semantics Syntax: The rules for writing programs. We will use Context Free

More information

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

Gene Kim 9/9/2016 CSC 2/444 Lisp Tutorial Gene Kim 9/9/2016 CSC 2/444 Lisp Tutorial About this Document This document was written to accompany an in-person Lisp tutorial. Therefore, the information on this document alone is not likely to be sufficient

More information

A Genetic Algorithm Implementation

A Genetic Algorithm Implementation A Genetic Algorithm Implementation Roy M. Turner (rturner@maine.edu) Spring 2017 Contents 1 Introduction 3 2 Header information 3 3 Class definitions 3 3.1 Individual..........................................

More information

Functional Languages. Hwansoo Han

Functional Languages. Hwansoo Han Functional Languages Hwansoo Han Historical Origins Imperative and functional models Alan Turing, Alonzo Church, Stephen Kleene, Emil Post, etc. ~1930s Different formalizations of the notion of an algorithm

More information

Functional Programming. Big Picture. Design of Programming Languages

Functional Programming. Big Picture. Design of Programming Languages Functional Programming Big Picture What we ve learned so far: Imperative Programming Languages Variables, binding, scoping, reference environment, etc What s next: Functional Programming Languages Semantics

More information

4/19/2018. Chapter 11 :: Functional Languages

4/19/2018. Chapter 11 :: Functional Languages Chapter 11 :: Functional Languages Programming Language Pragmatics Michael L. Scott Historical Origins The imperative and functional models grew out of work undertaken by Alan Turing, Alonzo Church, Stephen

More information

LECTURE 16. Functional Programming

LECTURE 16. Functional Programming LECTURE 16 Functional Programming WHAT IS FUNCTIONAL PROGRAMMING? Functional programming defines the outputs of a program as a mathematical function of the inputs. Functional programming is a declarative

More information

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

Scheme. Functional Programming. Lambda Calculus. CSC 4101: Programming Languages 1. Textbook, Sections , 13.7 Scheme Textbook, Sections 13.1 13.3, 13.7 1 Functional Programming Based on mathematical functions Take argument, return value Only function call, no assignment Functions are first-class values E.g., functions

More information

CSC 533: Programming Languages. Spring 2015

CSC 533: Programming Languages. Spring 2015 CSC 533: Programming Languages Spring 2015 Functional programming LISP & Scheme S-expressions: atoms, lists functional expressions, evaluation, define primitive functions: arithmetic, predicate, symbolic,

More information

Modern Programming Languages. Lecture LISP Programming Language An Introduction

Modern Programming Languages. Lecture LISP Programming Language An Introduction Modern Programming Languages Lecture 18-21 LISP Programming Language An Introduction 72 Functional Programming Paradigm and LISP Functional programming is a style of programming that emphasizes the evaluation

More information

Principles of Programming Languages Topic: Functional Programming Professor L. Thorne McCarty Spring 2003

Principles of Programming Languages Topic: Functional Programming Professor L. Thorne McCarty Spring 2003 Principles of Programming Languages Topic: Functional Programming Professor L. Thorne McCarty Spring 2003 CS 314, LS, LTM: Functional Programming 1 Scheme A program is an expression to be evaluated (in

More information

Scheme: Expressions & Procedures

Scheme: Expressions & Procedures Scheme: Expressions & Procedures CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, March 31, 2017 Glenn G. Chappell Department of Computer Science University

More information

Organization of Programming Languages CS3200/5200N. Lecture 11

Organization of Programming Languages CS3200/5200N. Lecture 11 Organization of Programming Languages CS3200/5200N Razvan C. Bunescu School of Electrical Engineering and Computer Science bunescu@ohio.edu Functional vs. Imperative The design of the imperative languages

More information

SCHEME AND CALCULATOR 5b

SCHEME AND CALCULATOR 5b SCHEME AND CALCULATOR 5b COMPUTER SCIENCE 6A July 25, 203 In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

A Quick Introduction to Common Lisp

A Quick Introduction to Common Lisp CSC 244/444 Notes last updated ug. 30, 2016 Quick Introduction to Common Lisp Lisp is a functional language well-suited to symbolic I, based on the λ-calculus and with list structures as a very flexible

More information

Project 2: Scheme Interpreter

Project 2: Scheme Interpreter Project 2: Scheme Interpreter CSC 4101, Fall 2017 Due: 12 November 2017 For this project, you will implement a simple Scheme interpreter in C++ or Java. Your interpreter should be able to handle the same

More information

Lecture #2 Kenneth W. Flynn RPI CS

Lecture #2 Kenneth W. Flynn RPI CS Outline Programming in Lisp Lecture #2 Kenneth W. Flynn RPI CS Items from last time Recursion, briefly How to run Lisp I/O, Variables and other miscellany Lists Arrays Other data structures Jin Li lij3@rpi.edu

More information

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

FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 2. ÚVOD DO LISPU: ATOMY, SEZNAMY, FUNKCE, FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 2. ÚVOD DO LISPU: ATOMY, SEZNAMY, FUNKCE, 2011 Jan Janoušek MI-FLP Evropský sociální fond Praha & EU: Investujeme do vaší budoucnosti L I S P - Introduction L I S P

More information

Putting the fun in functional programming

Putting the fun in functional programming CM20167 Topic 4: Map, Lambda, Filter Guy McCusker 1W2.1 Outline 1 Introduction to higher-order functions 2 Map 3 Lambda 4 Filter Guy McCusker (1W2.1 CM20167 Topic 4 2 / 42 Putting the fun in functional

More information

A Brief Introduction to Scheme (II)

A Brief Introduction to Scheme (II) A Brief Introduction to Scheme (II) Philip W. L. Fong pwlfong@cs.uregina.ca Department of Computer Science University of Regina Regina, Saskatchewan, Canada Lists Scheme II p.1/29 Lists Aggregate data

More information

15 Unification and Embedded Languages in Lisp

15 Unification and Embedded Languages in Lisp 15 Unification and Embedded Languages in Lisp Chapter Objectives Chapter Contents Pattern matching in Lisp: Database examples Full unification as required for Predicate Calculus problem solving Needed

More information

Chapter 15. Functional Programming Languages

Chapter 15. Functional Programming Languages Chapter 15 Functional Programming Languages Copyright 2009 Addison-Wesley. All rights reserved. 1-2 Chapter 15 Topics Introduction Mathematical Functions Fundamentals of Functional Programming Languages

More information

Fundamentals of Artificial Intelligence COMP221: Functional Programming in Scheme (and LISP)

Fundamentals of Artificial Intelligence COMP221: Functional Programming in Scheme (and LISP) Fundamentals of Artificial Intelligence COMP221: Functional Programming in Scheme (and LISP) Prof. Dekai Wu Department of Computer Science and Engineering The Hong Kong University of Science and Technology

More information

Allegro CL Certification Program

Allegro CL Certification Program Allegro CL Certification Program Lisp Programming Series Level I Session 1.3.1 David Margolies Manipulating Lists 9/16/2010 1 What is a List? An ordered (possibly empty) collection of things in a particular

More information

Artificial Intelligence Programming

Artificial Intelligence Programming Artificial Intelligence Programming Rob St. Amant Department of Computer Science North Carolina State University Lisp basics NC State University 2 / 99 Why Lisp? Some recent Lisp success stories include

More information

Chapter 1. Fundamentals of Higher Order Programming

Chapter 1. Fundamentals of Higher Order Programming Chapter 1 Fundamentals of Higher Order Programming 1 The Elements of Programming Any powerful language features: so does Scheme primitive data procedures combinations abstraction We will see that Scheme

More information

COP4020 Programming Assignment 1 - Spring 2011

COP4020 Programming Assignment 1 - Spring 2011 COP4020 Programming Assignment 1 - Spring 2011 In this programming assignment we design and implement a small imperative programming language Micro-PL. To execute Mirco-PL code we translate the code to

More information

CPS 506 Comparative Programming Languages. Programming Language Paradigm

CPS 506 Comparative Programming Languages. Programming Language Paradigm CPS 506 Comparative Programming Languages Functional Programming Language Paradigm Topics Introduction Mathematical Functions Fundamentals of Functional Programming Languages The First Functional Programming

More information

Principles of Programming Languages COMP251: Functional Programming in Scheme (and LISP)

Principles of Programming Languages COMP251: Functional Programming in Scheme (and LISP) Principles of Programming Languages COMP251: Functional Programming in Scheme (and LISP) Prof. Dekai Wu Department of Computer Science and Engineering The Hong Kong University of Science and Technology

More information

User-defined Functions. Conditional Expressions in Scheme

User-defined Functions. Conditional Expressions in Scheme User-defined Functions The list (lambda (args (body s to a function with (args as its argument list and (body as the function body. No quotes are needed for (args or (body. (lambda (x (+ x 1 s to the increment

More information

CS 314 Principles of Programming Languages

CS 314 Principles of Programming Languages CS 314 Principles of Programming Languages Lecture 16: Functional Programming Zheng (Eddy Zhang Rutgers University April 2, 2018 Review: Computation Paradigms Functional: Composition of operations on data.

More information

Lecture #5 Kenneth W. Flynn RPI CS

Lecture #5 Kenneth W. Flynn RPI CS Outline Programming in Lisp Lecture #5 Kenneth W. Flynn RPI CS We've seen symbols in three contexts so far: > (setf sym ) (let ((sym ))...) >'Sym SYM -- Context The first of these refers to a special (or

More information

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

Introduction to ACL2. CS 680 Formal Methods for Computer Verification. Jeremy Johnson Drexel University Introduction to ACL2 CS 680 Formal Methods for Computer Verification Jeremy Johnson Drexel University ACL2 www.cs.utexas.edu/~moore/acl2 ACL2 is a programming language, logic, and theorem prover/checker

More information

Scheme as implemented by Racket

Scheme as implemented by Racket Scheme as implemented by Racket (Simple view:) Racket is a version of Scheme. (Full view:) Racket is a platform for implementing and using many languages, and Scheme is one of those that come out of the

More information

Evaluating Scheme Expressions

Evaluating Scheme Expressions Evaluating Scheme Expressions How Scheme evaluates the expressions? (procedure arg 1... arg n ) Find the value of procedure Find the value of arg 1 Find the value of arg n Apply the value of procedure

More information

Robot Programming with Lisp

Robot Programming with Lisp 4. Functional Programming: Higher-order Functions, Map/Reduce, Lexical Scope Institute for Artificial University of Bremen 9 of November, 2017 Functional Programming Pure functional programming concepts

More information

Introductory Scheme. Revision 1

Introductory Scheme. Revision 1 Introductory Scheme Revision 1 Joseph W. Lavinus and James D. Arthur (lavinus@cs.vt.edu and arthur@cs.vt.edu) Department of Computer Science Virginia Polytechnic Institute and State University Blacksburg,

More information

A little bit of Lisp

A little bit of Lisp B.Y. Choueiry 1 Instructor s notes #3 A little bit of Lisp Introduction to Artificial Intelligence CSCE 476-876, Fall 2017 www.cse.unl.edu/~choueiry/f17-476-876 Read LWH: Chapters 1, 2, 3, and 4. Every

More information

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1 A First Look at ML Chapter Five Modern Programming Languages, 2nd ed. 1 ML Meta Language One of the more popular functional languages (which, admittedly, isn t saying much) Edinburgh, 1974, Robin Milner

More information

Documentation for LISP in BASIC

Documentation for LISP in BASIC Documentation for LISP in BASIC The software and the documentation are both Copyright 2008 Arthur Nunes-Harwitt LISP in BASIC is a LISP interpreter for a Scheme-like dialect of LISP, which happens to have

More information

Announcements. Today s Menu

Announcements. Today s Menu Announcements 1 Today s Menu Finish Introduction to ANNs (original material by Dr. Mike Nechyba) > Slides 58-60 > Adjusting the Learning Rate Loose Ends in > Lambda Expressions Review > I/O Functions >

More information

Look at the outermost list first, evaluate each of its arguments, and use the results as arguments to the outermost operator.

Look at the outermost list first, evaluate each of its arguments, and use the results as arguments to the outermost operator. LISP NOTES #1 LISP Acronymed from List Processing, or from Lots of Irritating Silly Parentheses ;) It was developed by John MacCarthy and his group in late 1950s. Starting LISP screen shortcut or by command

More information

Reasoning About Programs Panagiotis Manolios

Reasoning About Programs Panagiotis Manolios Reasoning About Programs Panagiotis Manolios Northeastern University March 22, 2012 Version: 58 Copyright c 2012 by Panagiotis Manolios All rights reserved. We hereby grant permission for this publication

More information

Introduction to Lisp

Introduction to Lisp Last update: February 16, 2010 Introduction to Lisp Dana Nau Dana Nau 1 Outline I assume you know enough about computer languages that you can learn new ones quickly, so I ll go pretty fast If I go too

More information

Lambda Calculus see notes on Lambda Calculus

Lambda Calculus see notes on Lambda Calculus Lambda Calculus see notes on Lambda Calculus Shakil M. Khan adapted from Gunnar Gotshalks recap so far: Lisp data structures basic Lisp programming bound/free variables, scope of variables Lisp symbols,

More information

Chapter 11 :: Functional Languages

Chapter 11 :: Functional Languages Chapter 11 :: Functional Languages Programming Language Pragmatics Michael L. Scott Copyright 2016 Elsevier 1 Chapter11_Functional_Languages_4e - Tue November 21, 2017 Historical Origins The imperative

More information

INF4820. Common Lisp: Closures and Macros

INF4820. Common Lisp: Closures and Macros INF4820 Common Lisp: Closures and Macros Erik Velldal University of Oslo Oct. 19, 2010 Erik Velldal INF4820 1 / 22 Topics for Today More Common Lisp A quick reminder: Scope, binding and shadowing Closures

More information

Allegro CL Certification Program

Allegro CL Certification Program Allegro CL Certification Program Lisp Programming Series Level I Review David Margolies 1 Summary 1 A lisp session contains a large number of objects which is typically increased by user-created lisp objects

More information

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia CPL 2016, week 10 Clojure functional core Oleg Batrashev Institute of Computer Science, Tartu, Estonia April 11, 2016 Overview Today Clojure language core Next weeks Immutable data structures Clojure simple

More information

Fifth Generation CS 4100 LISP. What do we need? Example LISP Program 11/13/13. Chapter 9: List Processing: LISP. Central Idea: Function Application

Fifth Generation CS 4100 LISP. What do we need? Example LISP Program 11/13/13. Chapter 9: List Processing: LISP. Central Idea: Function Application Fifth Generation CS 4100 LISP From Principles of Programming Languages: Design, Evaluation, and Implementation (Third Edition, by Bruce J. MacLennan, Chapters 9, 10, 11, and based on slides by Istvan Jonyer

More information

Functional Languages. CSE 307 Principles of Programming Languages Stony Brook University

Functional Languages. CSE 307 Principles of Programming Languages Stony Brook University Functional Languages CSE 307 Principles of Programming Languages Stony Brook University http://www.cs.stonybrook.edu/~cse307 1 Historical Origins 2 The imperative and functional models grew out of work

More information

CSCC24 Functional Programming Scheme Part 2

CSCC24 Functional Programming Scheme Part 2 CSCC24 Functional Programming Scheme Part 2 Carolyn MacLeod 1 winter 2012 1 Based on slides from Anya Tafliovich, and with many thanks to Gerald Penn and Prabhakar Ragde. 1 The Spirit of Lisp-like Languages

More information

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?

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? More Scheme CS 331 Quiz 1. What is (car ((2) 3 4))? (2) 2. What is (cdr ((2) (3) (4)))? ((3)(4)) 3. What is (cons 2 (2 3 4))? (2 2 3 4) 4. What is the length of the list (()()()())? 4 5. Which element

More information

(Func&onal (Programming (in (Scheme)))) Jianguo Lu

(Func&onal (Programming (in (Scheme)))) Jianguo Lu (Func&onal (Programming (in (Scheme)))) Jianguo Lu 1 Programming paradigms Func&onal No assignment statement No side effect Use recursion Logic OOP AOP 2 What is func&onal programming It is NOT what you

More information

History. Functional Programming. Based on Prof. Gotshalks notes on functionals. FP form. Meaningful Units of Work

History. Functional Programming. Based on Prof. Gotshalks notes on functionals. FP form. Meaningful Units of Work History Functional Programming Based on Prof. Gotshalks notes on functionals 1977 Turing 1 Lecture John Backus described functional programming The problem with current languages is that they are word-at-a-time

More information

1 of 5 5/11/2006 12:10 AM CS 61A Spring 2006 Midterm 2 solutions 1. Box and pointer. Note: Please draw actual boxes, as in the book and the lectures, not XX and X/ as in these ASCII-art solutions. Also,

More information

UMBC CMSC 331 Final Exam

UMBC CMSC 331 Final Exam UMBC CMSC 331 Final Exam Name: UMBC Username: You have two hours to complete this closed book exam. We reserve the right to assign partial credit, and to deduct points for answers that are needlessly wordy

More information

(defun fill-nodes (nodes texts name) (mapcar #'fill-node (replicate-nodes nodes (length texts) name) texts))

(defun fill-nodes (nodes texts name) (mapcar #'fill-node (replicate-nodes nodes (length texts) name) texts)) PROBLEM NOTES Critical to the problem is noticing the following: You can t always replicate just the second node passed to fill-nodes. The node to be replicated must have a common parent with the node

More information

Functional Programming Languages (FPL)

Functional Programming Languages (FPL) Functional Programming Languages (FPL) 1. Definitions... 2 2. Applications... 2 3. Examples... 3 4. FPL Characteristics:... 3 5. Lambda calculus (LC)... 4 6. Functions in FPLs... 7 7. Modern functional

More information

CS 314 Principles of Programming Languages. Lecture 16

CS 314 Principles of Programming Languages. Lecture 16 CS 314 Principles of Programming Languages Lecture 16 Zheng Zhang Department of Computer Science Rutgers University Friday 28 th October, 2016 Zheng Zhang 1 CS@Rutgers University Class Information Reminder:

More information