Many versions: Franz, Mac, Inter, Common (now the

Size: px
Start display at page:

Download "Many versions: Franz, Mac, Inter, Common (now the"

Transcription

1 Intro to Lisp LISP = LISt Processing Originated w/ McCarthy (1959) Implemented Church's lambda-calculus (recursive function theory) Manipulation of symbolic information The initial Lisp was impractical (no iteration) Many versions: Franz, Mac, Inter, Common (now the standard) Guy Steele (1990): VERY useful reference. 12

2 Why Lisp? First, Lisp is much more exible than most languages. Users have such total control over what goes on that if they do not like the syntax of the language, they may change it to suit themselves. Suppose that you do not like the method for dening programs in, say, Fortran, can you do anything about it? Short of switching to another language the answer is clearly no. Indeed the very idea seems absurd. But not to Lisp users. (Spector, 1995, PC.)...The second reason for choosing lisp is the way in which Lisp in oriented toward the manipulation of symbols as opposed to, say, numbers.norvig, (PoAIP, p. 25): What is it that sets Lisp apart from other languages? Why is it a good language for AI applications? There are at least seven important factors (from Norvig): Built-in Support for Lists Automatic Storage Management Dynamic Typing First-Class Functions Uniform Syntax Interactive Environment Extensibility 13

3 Characteristics of Lisp Interactive (somewhat supercially), Recursive, Very simple syntax (does automatic memory mgmt), variables not explicitly typed, may be interpreted or compiled. Oriented toward: (1) non-numeric symbol manipulation (2) structure building and modication. Programs and data have same form Lisp is the defacto standard language in AI 14

4 Some dierences between Lisp and Conventional Languages Symbolic Processing Structure Building and Modication Not only assigns values to symbols, but also permits dynamic construction and dissection of data structures Programs and data have same form Can construct pgms on the y and even use them Additional dierences (noted in Norvig) Many langs distinguish between stmts and expressions. Statements have eects (x = 2 + 2). Expressions return values (2 + 2). In Lisp, ALL every expression returns a value Some of those expressions also have side eects. Lexical rules are very simple. Fewer punctuation chars, only parens and white space. x=2+2 is one single symbol need to insert spaces: (x=2+2) to separate the symbols. No need for semicolons as a delimiter. Expressions delimited byparentheses. (Semi colons are for comments.) 15

5 Syntax of Lisp Lisp is based on symbolic expressions or S-expressions: An atom is an S-expression: (a) symbol (b) non-symbol (number, string, array) Examples: X, JOHN, SETQ, 7.2, "John" Alist is an S-expression: (S-expr S-expr :::) Examples: (+ 1 2), (A (B C)) Note: case insensitive THAT'S ALL THERE IS TO THE SYNTAX!!! (except for dot notation and special characters we'll get to special chars later). S-expression atom list dotted pair symbol, number, string, character, array (a b 3) (3. a) (a. (b. (3. nil))) Note: A list is a special case of a dotted pair where the last cell = NIL So, actually: an S-expression is either an atom or a dotted pair. So (A) is an abbrev for (A. NIL). Lists more commonly used than dotted pairs (convenient). Note: (nil. nil) = ((). ()) = ((). nil) = (()) 6= nil 16

6 Sit in front of terminal Enter Lisp (interactive) Basic Idea of Using Lisp Now you're in a read-eval-print loop EVAL = give me an expression to evaluate returns a value for an s-expr. (analogy: words in sentences vs. meaning) Lisp reads the S-expr, evaluates the S-expr, then prints the result of the evaluation. 17

7 Atoms and Lists Atoms: atom turkey turkeys *abc Lists: (atom) (atom turkey) (atom 1492 ocean blue) (an-atom (a list inside) and more atoms) (a list containing 5 atoms) (a list containing 8 atoms and a list (that contains 4 atoms)) (((a list containing a list containing a list of 11 atoms))) () (a list that ends with the null list ()) (not a list (not) a list )not again The Lisp evaluation rule: To evaluate an atom: If it is a numeric atom, the value is the number Else it must be a variable symbol so the value is the value of the variable To evaluate a list: Assume the first item of the list is a function, and apply that function to the values of the remaining elements of the list. 18

8 Result of Evaluation: What is the value? Number! number itself (e.g., 7! 7) String! string itself (e.g., "hi"! "hi") Symbol! value of symbol (e.g., X! 5, if X has that value) Symbols like variables in most langs, have a value associated with them. Special: T, NIL List! normally function evaluation Normally write fcn as f(a,b,: ::,n) or inx a+b+: ::+n In Lisp: put f inside left paren: (f a b ::: n) By convention, we assume that when given a list to evaluate, the rst atom has a value associated with it which is the body of a function. ([name of fn] [args]) (+12)! 3 First elt of list is special: applied to rest of elts. Evaluation of list: (1) eval each elt of list (rst elt should return fcn body, rest return args) (2) apply fcn from 1st atom to rest. Important Note: use 'to indicate \the S-expr stated" rather than the value of that S-expr. (e.g., 'X returns X, whereas X returns the value stored in X). We'll run through what a sample session looks like ina minute. 19

9 Examples: Quote symbol '2! 2 2! 2 'John! John John! ERROR: not a bound variable Quote: use ' to indicate \the S-expression stated" rather than the value of that S-expression. Serves to BLOCK evaluation of following expression, returning it literally. Example: '(Pat Kim)! (PAT KIM) If we just had (Pat Kim), it would consider Pat as a function and apply it to the value of the expression Kim. 20

10 Sample Session Fire up Lisp... (+ 1 1) => 2 (* 23 13) => 299 (+ 1 (* 23 13)) => 300 (+ (* 2 2) (- 10 9)) => 5 (* ) => 16 (sqrt (* )) => 4 (/ 25 5) => 5 (/ 38 4) => 19/2 "Hello, world!" => "Hello, world!" 'x => X x Can abort out of this (abort current => Error: Unbound variable X computation and return to read-eval-print loop) 21

11 Sample Session (continued) (setf x 5) Setf gives a value to a variable. It has a side => 5 effect and ALSO returns a value (setf y (reverse '(+ a b))) Reverse reverses a list. => (B A +) (setf l '(a b c d e)) => (A B C D E) l's value will now be a list. (length l) length --> gives length of a list => 5 (append l '(f)) append --> merges to lists together => (A B C D E F) (Note use of quote l not quoted) (length l) => 5 Note that the length of l has not changed. (length (append '(pat Kim) (list '(John Q Public) 'Sandy))) => 4 Symbolic computations can be nested and mixed with numeric computations. Note: "list" puts elts into a list doesn't merge them like "append" does. Note: Order of evaluation critical. (Eval args first.) Note: Parens MUST match --> source of bizarre errors if not. (car l) (first l) => A (cdr l) (rest l) => (B C D E) (first (rest l)) => B (cons 'q l) MAIN CONSTRUCTOR used in Lisp. => (Q A B C D E) 22

12 Understanding LISP: Lisp Data Structures Best way to understand Lisp: Develop an intuitive understanding of its data structures (remember: pgms and data stored the same way). First step: forget conventional pgming langs w/ which you are familiar (else confusion). Three notations for Lisp data structures: (1) paren/list (printed) (2) dot (printed only if req list notation is abbrev. for this) (3) pictorial or graphic or box/cell notation (never printed shows what's going on inside). We will return to relate these three. Note: parenthesized notation = surface appearance (typing in/out at terminal) whereas pictorial notation = what's happening below the surface (i.e., how the computer is really doing it). Need to be able to switch back and forth between these two easily. 24

13 Pictorial Notation: used to describe what goes on in Memory CONS Cell: A cell in memory (w/ left and right halves) Note: combinations of CAR/CDR (up to 4), e.g., CADR = (CAR (CDR..)) A B A A B (CONS A B) CAR = A Note: No SIDE EFFECT (important later) B CDR = B Also: FIRST, SECOND,... TENTH (car,cadr,caddr,...) These are off in memory Difference Between: CONS, LIST, APPEND nil nil A B (CONS A B) (LIST A B) Adds one mem cell Adds one mem cell for each elt (A. B) (A B) Note: can have (CONS A NIL)-> (A) A B Note: can have (LIST A) -> (A) A B (APPEND (A) (B)) All args must be lists! Last ptr of each elt points to next elt (A B) same Suppose: X = (A) Y = (B) What is (CONS X Y)? What is (LIST X Y)? B nil nil A nil (CONS X Y) = ((A) B) A nil B nil (LIST X Y) = ((A) (B)) 25

14 Quote (continued from last time) The quote function inhibits the evaluation of its argument. It returns its argument literally. If the variable barney has the value 22, then: Evaluating barney yields 22 Evaluating (quote barney) yields barney Evaluating (car (quote yields betty (betty bambam))) The single quote mark (') (it is actually an apostrophe) can be used as an abbreviation for (quote...). 2

15 Taking lists apart (continued from last time) The rst element of a list (be it an atom or another list) is the car of the list. (car '(alphabet => alphabet soup)) (car '((pickles beer) alphabet (soup))) =>(pickles beer) (car '(((miro (braque picasso))) leger)) =>((miro (braque picasso))) Everything except the rst element of a list is the cdr of the list. (cdr '(alphabet =>(soup) soup)) (cdr '((pickles beer) alphabet (soup))) => (alphabet (soup)) (cdr '(((miro (braque picasso))) leger)) =>(leger) Given a complex S-expression, you can obtain any of its component S-expressions through some combination of car and cdr. cadr is the car of the cdr: (cadr '(old mcdonald =>MCDONALD had a farm)) cdar is the cdr of the car: => (cdar '((do you)(really think so?))) (YOU) There are more variations, at least up to 4 a's or d's: (caddar '((deep (in the (nested) lies truth))) => LIES structure) 3

16 Taking lists apart (continued) rst is a synonym for car second is a synonym for cadr third is a synonym for caddr... rest is a synonym for cdr (setf x '(eenie meenie minie moe)) => (EENIE MEENIE MINIE MOE) (first x) => EENIE (third x) => MINIE (rest x) => (MEENIE MINIE MOE) The null list: (cdr '(just-one-item)) => NIL '() => NIL 4

17 cons builds lists. (cons 'woof '(bow wow)) => (woof bow wow) (cons '(howl) '(at the moon)) => ((howl) at the moon) Putting lists together You can create any list with cons. (cons 'naked-atom => (NAKED-ATOM) (cons 'naked-atom =>(NAKED-ATOM) '()) nil) car, cdr, and cons are all non-destructive: (setf x '(the rain in spain)) =>(THE RAIN IN SPAIN) (car x) =>THE (cdr x) =>(RAIN IN SPAIN) (cons 'darn x) =>(DARN THE RAIN IN SPAIN) x =>(THE RAIN IN SPAIN) 5

18 Atoms and Dotted Pairs (continued from last time) You get errors if you try to take thecaror cdr of a non-nil atom (car 'foo) => > Error: Can't take CAR of FOO. (cdr 'foo) => > Error: Can't take CDR of FOO. You get \funny dots" if you try to cons things onto non-lists (cons 'a 'b) => (A. B) Although \dotted pairs" have their uses, we mostly won't use them beyond the rst problem set. That means that you're probably doing something wrong if you get dots in your answers. 6

19 Earlier dialects: Generalized assignment (setf) setq) setq assigns a value to a symbol not available (used something called (setq my-favorite-list => (fe fi fo fum) my-favorite-list => (fe fi fo fum) '(fe fi fo fum)) setq is an exception to the normal evaluation rule the rst argument is not evaluated. (q = quote) But setq cannot be used for generalized vars! rplaced with setf. A generalized var refers to any place a ptr may bestored. A "A has the value (3)" A 3 nil 3 "A has the value 3" Other places a ptr can be stored? car/cdr of cons cell Asst! replacing one ptr with another (setf A (4)) (setf (car A) 4) A A 3 nil 4 nil 3 nil 4 Can use an accessor such as CAR, CDR, FIRST, etc. "A has the value (4)" 7

20 More about setting variables Lisp doesn't need type declaration because everything is a pointer (i.e., the values of symbols have types associated w/ them atoms, lists, integers, etc.) Typical memory org: Lisp system Cons nodes Strings Integers Symbols Symbol: \indivisible atoms" actually have parts. Typically each atom is a table: X Name Value Function Prop List Package "X" (string -- not same as symbol) (if nothing here, atom is unbound) (function definition) What does setf do? (setf x 7) Changes value slot of X's table to point to 7 Can access slots: (symbol-name 'reverse)! "reverse" (symbol-function 'reverse)! #<compiled-fn reverse> 8

21 Eval EVAL = explicit evaluation. (+ 3 5)! evaluated w/o user explicitly asking for eval'n EVAL is applied by the system (LISP = read-eval-print loop) Explicit eval = extra evaluation Sort of the opposite of quote. Examples: Suppose (setf x 'y), (setf y 'z) x! y (eval x)! z (eval 'x)! y What is eval useful for? { retrieving value of symbol whose name is not known until runtime: (setfa3) (eval 'a)! 3 NOT REALLY A GOOD IDEA: Can use symbol-value no reason to use eval. { evaluating form that is constructed at runtime: (eval (list <fn> args...)) (eval (list 'setf arg1 arg2)) (where arg1='x and arg2=3) evaluates (setf x 3) Note: basically building a (trivial) function and running it on the y in the \old" days, this was considered the \key" to Lisp's exibility NOT REALLY A GOOD IDEA: Use symbol-value again: (setf (symbol-value 'arg1) (symbol-value 'arg2)) But might be cases where don't have enough info if the list '(setf x 3) is passed into a fn to be evaluated, then probably best thing to do is eval: (1) can't use funcall/apply cause setf is macro (2) don't know enough about the args w/o extensive testing to be able to use (or in this case not use) symbol-value. But in general, we no longer need eval, really. Some people (e.g., Norvig) say you're doing something wrong if you use it. But you should know it is there, and that sometimes there's no choice. 9

22 Comments Common Lisp provides 2 ways to comment your code: # this could be a really big comment # (car '(a b c)) this is a comment => A (cdr '(here is # a list with a comment # huh?)) => (IS HUH?) 10

23 Commonlisp Forms Function: (+35) Can test with (functionp x) Note: Arguments to a function can themselves be a function (nesting): (+ (* 3 5) 5) Macro: (setf x 1) Can test with (macro-function x) Note: violates eval'n rule: don't eval x, only eval 1. Special form: (if test a b) Can test with (special-form x) Two others we'll learn about later: let, let* We'll initially concentrate on this rst type of form (the function). We'll talk about macros in detail later. 11

24 Predicates A Predicate is a function that is called to answer a yes-or-no question. A predicate returns boolean truth values (T = true / NIL = false) T/NIL special symbols predened to have self as value. (The atom t means true, and evaluates to itself. The atom NIL means false, and evaluates to itself.) Predicates may return t for true, or they may return any other non-nil value. Predicates in Common Lisp take various forms, but often end with p. 12

25 Predicates (continued) 1. <, > (numeric functions) 2. macros may serve as predicates: (AND t nil), (OR t nil) Note: implementation of these allows them to be control constructs (and nil t t t) stop at rst nil, (or t nil nil nil) stop at rst t. Note: Generally considered poor style to use and/or for side eect: (or (setf x (<fn>...)) (setf x 'fail)) should use to test logical condition. 3. (atom x), (null x), (not x), (listp x), (consp x), (numberp x), (stringp x), (arrayp x), (vectorp x), (characterp x), (member x y :test <test>) Note: All conses are lists, but converse not true: (consp nil)! nil Note: Member doesn't just return t or nil! 13

26 (null 'fig-tree) => NIL (null '(bismark)) => NIL (null '()) => T (null ()) => T (null nil) => T (atom 'eggplant) => T (atom 99) => T (atom ) => T (atom '(floating point number)) => NIL (atom nil) => T (atom ()) => T (listp 'apple) => NIL (listp '(fish and telephones)) => T (listp 33) => NIL (listp nil) => T (setq lucky-number 23) => 23 (evenp lucky-number) => NIL (not (evenp lucky-number)) => T Sample Session: Predicates 14

27 Sample Session: Predicates Taking More Than One Argument (> 22 11) => T (> 11 22) => NIL (<= 23 23) => T (>= 23 23) => T (>= 100 1) => T (>= 1 100) => NIL (< ) => T (< ) => NIL 15

28 Equality Common lisp has a variety of Equality Predicates, of which equalp is the most general (see CLtL2 p. 103). And, or, and not allow the combination of predicates into complex predicates. EQ and EQUAL { two most commonly used. EQ tests whether args eval to exact same Lisp obj EQUAL compares any two s-expressions (lists, strings, etc.) = used for numbers (must be same number) EQL: EQ or = EQUALP same as EQUAL but disregards case (for strings). Others: tree-equal, char-equal, string-equal, string=, char= Note: these are all a special case of equal Tree-equal tests whether two trees are equal except that the leaf nodes are expected to be symbol atoms (not, eg., strings) Note: can specify :TEST such as string=. x y = eq eql equal equalp 'x 'x err T T T T '0 '0 T? T T T '(x) '(x) err nil nil T T '"xy" '"xy" err nil nil T T '"Xy" '"xy" err nil nil nil T '0 '0.0 nil nil nil nil T '0 '1 nil nil nil nil nil 16

29 Equality: Need to think about what's happening in memory So far: S-exprs drawn so that symbol referenced more than once drawn multiple times in memory What s really going on? nil nil A B A B EQ A In reality, both pointers to A point to the SAME symbol (i.e., the same exact mem location) EQ: tests for memory location exactly therefore, atoms only! LISP automatically makes sure that all refs to some symbol actually point to the UNIQUE point in mem that the symbol happens to be stored physically. This way, any info stored w/ it (e.g., its value) is accessible from every ref. Anytime LISP sees new symbol, it adds the symbol to its storehouse of known atoms. 17

30 Sample Session: Equality (equalp 'foot 'foot) => T (equalp 'nose 'ear) => NIL (equalp ( ) (* 33 3)) => T (setq long-list '( can I show you out the door?)) => ( CAN I SHOW YOU OUT THE DOOR?) (setq lucky-number 23) => 23 (or (equalp lucky-number (car long-list)) (equalp (* (car long-list) 2) (car (cdr long-list)))) => T (and (equalp lucky-number (car long-list)) (equalp (* (car long-list) 2) (car (cdr long-list)))) => NIL 18

31 Conditionals IF: special form (if (= x 21) (print 'blackjack)) WHEN: macro has same form: (when (= x 21) (print 'blackjack)) Dierence: IF has else part should use if only when there is an else part! (if z 'not-empty 'empty) [z is a boolean] IF: most useful for 2-way fork where then/else are each 1 expr WHEN: used for 1-way fork (then may bemore than 1 expr) What if more than 2-way fork? Use COND! (cond (C 1 ( E 11 E 21...)) (if C E 1 E 2 ) C N Y E 1 (C 2 (E 21 E 22...))... (C n (E n1 E n2...))) C Y E 1 11 E E 2 N (when C E 1 E 2 ) C 1 Y E 11 E C Y E 1 E 2... C Y E n n1 E n2... COND: Powerful multiway branching construct Arbitrary number of args (called clauses) Note: general form! can have more than one action. Each clause is a list of s-exprs Example: (Ci Ei1 Ei2... Eim). Value returned : Eim, where C i is rst non-nil condition (No more Ci or Ei's are evaluated.) Convention for our class: last Ci is the constant T (guaranteed to be non-nil). 19

32 Conditionals: Examples (cond (x 'b) (y 'c) (t 'd)) What if x = 'a? (then returns b) What if x = nil, y = t? (then returns c) What if x = nil y = nil? (then returns d) (cond (x (setf x 1) (+ x 2)) (y (setf y 2) (+ y 2)) (t (setf x 0) (setf y 0))) What if x = t? (then returns 3) What is x? (x = 1) What if x = nil, y = t? (then returns 4) What are x/y? (nil/2) What if x = nil y = nil? (then returns 0) What are x/y? (0/0 Note: could also do the following: (cond (x (setf x 1) (+ x 2)) ((setf y 2))) If x is nil, then it'll execute the last statement and return it. Other conditionals (chapter 3): (case (expression (match 1 result 11 result 12...) (match 2 result 21 result 22...)... (matchn result n1 result n2...))) Note: use \otherwise" as last match expression. Can also use OR and AND as conditional control constructs (as we talked about earlier): (and nil t t t), (or t nil nil nil) 20

33 IF vs. COND The IF special form is a special case of COND: IF testform thenform [elseform] Evaluates testform. If the result is true, evaluates thenform and returns the result if the result is nil, evaluates elseform and returns the result. (if (> ) 'sure-is => SURE-IS 'sure-aint) (if (member 'bog '(blig blog bog bumper)) (* 99 99) (sqrt -1)) => 9801 (if (member 'fog '(blig blog bog bumper)) (* 99 99) (sqrt -1)) => #c(0 1) Note that the thenform and the elseform are both restricted to being single forms. In contrast, you can specify any numberofforms in a cond clause: (setq temperature 8) => 8 (cond ((< temperature 32) (t (print '(yowch -- it is cold!)) (print '(i will play god and change that!)) (setq temperature 78)) (print '(well i guess it is not so bad)) (print '(where do you think (YOWCH -- IT IS COLD!) we are? hawaii?)))) (I WILL PLAY GOD AND CHANGE THAT!) => 78 21

34 PROGN If you want multiple formsinanifyou can use a PROGN: Evaluates each form in order, left to right. The values of all forms but the last are discarded the value of the last form is returned. (if (< temperature 32) (progn (print '(yowch -- it is cold!)) (print (progn (print '(i will play god and change that!)) (setq temperature 78)) '(well i guess it is not so bad)) (print '(where do you think we are? hawaii?)))) (WELL I GUESS IT IS NOT SO BAD) (WHERE DO YOU THINK WE ARE? HAWAII?) => (WHERE DO YOU THINK WE ARE? HAWAII?) 22

35 Sample Session: COND (setq x 23) => 23 (cond ((equalp x 1) '(it was one)) ((equalp x 2) '(it was two)) (t '(it was not one or two))) => (IT WAS NOT ONE OR TWO) (setq x 2) => 2 (cond ((equalp x 1) '(it was one)) ((equalp x 2) '(it was two)) (t '(it was not one or two))) => (IT WAS TWO) 23

36 Dening Functions Dene Function = \Defun" (defun function-name (parameter...) function-body) Function name = symbol parameters usually symbols. (defun rst-name (name) (rst name)) (rst-name '(john q public))! JOHN 24

37 Sample Session: Defun Here's a function that takes one argument and returns the argument plus 20: (defun add-20 (n) "returns n + 20" (+ n 20)) => ADD-20 (add-20 15) => 35 Note the use of a documentation string in the function above. The string is not obligatory and does not aect the execution of the function, but it provides information about the function which can be accessed through the builtin functions \documentation" and \describe". (documentation 'add-20 'function) => returns n + 20 (describe 'add-20) => ADD-20 is a symbol. Its home package is USER. Its global function definition is #<Interpreted-Function ADD-20 FB0C26>... Its source code is (NAMED-LAMBDA ADD-20 (N) (BLOCK ADD-20 (+ N 20)))... It has this function documentation: "returns n + 20"... The semicolon comment follows a convention: (1) Preface description of function with three semicolons (2) Preface lines inside of a function with two semicolons (3) Preface minor comments at end of line with two semicolons. The function (defun test () TEST runs a demonstration. "Runs a test of SOLVE-PROBLEM." (setf x 'test-data) Assign X some test data. Call the main function. (solve-problem x)) 25

38 Sample Session: Defun (continued) Here's a constant function that takes no arguments (defun dumb-function () '(you might as well use a variable for something like this)) => DUMB-FUNCTION (dumb-function) => (YOU MIGHT AS WELL USE A VARIABLE FOR SOMETHING LIKE THIS) Here's a NON-constant function that takes no arguments (defun rand8 () (random 8)) => RAND8 (rand8) => 0 (rand8) => 6 (rand8) => 4 Note: \random" is a pseudo random number generator that takes a number and returns a value between zero (inclusive) and the number (exclusive). Here's a function using COND that returns an atom indicating whether its argument is even or odd (or not a number). (defun even-or-odd? (n) "returns 'even if n is even, 'odd if n is odd, and 'neither if n is not an in (cond ((not (integerp ((evenp => EVEN-OR-ODD? n) 'even) ((oddp n) 'odd))) n)) 'neither) (even-or-odd? 24) => EVEN (even-or-odd? 25) => ODD (even-or-odd? '(swahili)) => NEITHER 26

39 Sample Session: Defun (continued) Here's a function that takes two arguments and returns their sum: (defun my-sum (n1 n2) "silly substitute for +" (+ n1 n2)) => MY-SUM (my-sum ) => 199 Here's a version of + that also sets the global variable *lastsum*: (defun +store (n1 n2) "Returns the sum of n1 and n2, and also sets *last-sum* to the (setq *last-sum* (+ n1 n2))) => +STORE (+store ) => 199 *last-sum* => 199 Here's a function that takes 3 arguments and returns a descriptive list: (defun funny-arg-lister (arg1 arg2 arg3) (cons (cons 'arg1 (cons arg1 nil)) (cons (cons 'arg2 (cons arg2 nil)) (cons (cons 'arg3 (cons arg3 nil)) nil)))) => FUNNY-ARG-LISTER (funny-arg-lister 'a 'b '(x y z)) => ((ARG1 A) (ARG2 B) (ARG3 (X Y Z))) 27

40 Sample Session: Defun (continued) Here's a cleaner version of funny-arg-lister using the LIST function: (defun funny-arg-lister (arg1 arg2 arg3) (list (list 'arg1 arg1) (list 'arg2 arg2) (list 'arg3 arg3))) => FUNNY-ARG-LISTER (funny-arg-lister 'a 'b '(x y z)) => ((ARG1 A) (ARG2 B) (ARG3 (X Y Z))) Here's another simple function (defun double-cons (one-thing another-thing) "Returns the result of consing one-thing onto another-thing twic (cons one-thing (cons one-thing another-thing))) => DOUBLE-CONS (double-cons 'hip '(hooray)) => (HIP HIP HOORAY) (double-cons 1 nil) => (1 1) (double-cons 1 (double-cons 1 nil)) => ( ) (defun quadruple-cons (one-thing another-thing) "Returns the result of consing one-thing onto another-thing 4x" (double-cons one-thing (double-cons one-thing another-thing))) => QUADRUPLE-CONS (quadruple-cons 'um '(huh?)) => (UM UM UM UM HUH?) 28

41 Sample Session: Defun (continued) Function arguments are LOCAL variables (setq shoes 'nikes) => NIKES (defun run (shoes) (print (append '(i think i will take a trot in my) (list shoes))) (setq shoes (append '(old beat-up) (list shoes))) (print (append '(i think i will take a trot in my) shoes))) => RUN (run shoes) (I THINK I WILL TAKE A TROT IN MY NIKES) (I THINK I WILL TAKE A TROT IN MY OLD BEAT-UP NIKES) => (I THINK I WILL TAKE A TROT IN MY OLD BEAT-UP NIKES) (print 'foo) => FOO (defun run (shoes) this version returns '(I RAN) (print (append '(i think i will take a trot in my) (list shoes))) (setq shoes (append '(old beat-up) (list shoes))) (print (append '(i think i will take a trot in my) shoes)) '(i ran)) => RUN (run shoes) (I THINK I WILL TAKE A TROT IN MY NIKES) (I THINK I WILL TAKE A TROT IN MY OLD BEAT-UP NIKES) => (I RAN) shoes => NIKES 29

42 Sample Session: Operations on Lists The NTH function returns an element of a list by number (setq animals '(giraffe dog dinosaur bug big-bug big-hairy-bug)) => (GIRAFFE DOG DINOSAUR BUG BIG-BUG BIG-HAIRY-BUG) (nth 0 animals) => GIRAFFE (nth 1 animals) => DOG (nth 2 animals) => DINOSAUR (nth 3 animals) => BUG (nth 4 animals) => BIG-BUG (nth 5 animals) => BIG-HAIRY-BUG (nth 6 animals) => NIL The LENGTH function returns the number of elements in a list (length animals) => 6 (length '(the (deeper (you (go (the (nuller (you (get))))))))) => 2 30

43 Sample Session: Operations on Lists (continued) Here's a function to return a random element of a list (defun random-elt (choices) "returns one element of the list of choices at random" (nth (random (length choices)) choices)) => RANDOM-ELT (random-elt animals) => BUG (random-elt animals) => BIG-BUG This returns a random element as a singleton list (defun one-of (set) "picks one element of the set and returns it in a list" (list (random-elt set))) => ONE-OF (one-of '(how are you doing today?)) => (YOU) 31

44 Programming Example (Taken from Chapter 2 of Norvig, (PoAIP)) A Grammar for a (miniscule) Subset of English: Sentence => Noun-Phrase + Verb-Phrase Noun-Phrase => Article + Noun Verb-Phrase => Verb + Noun-Phrase Article => the, a,... Noun => man, ball, woman, table... Verb => hit, took, saw, liked... The grammar can be used to generate sentences: To get a Sentence, append a Noun-Phrase and a Verb-Phrase To get a Noun-Phrase, append an Article and a Noun Choose "the" for the Article Choose "man" for the Noun The resulting Noun-Phrase is "the man" To get a Verb-Phrase, append a Verb and a Noun-Phrase Choose "hit" for the Verb [etc.] The grammar can be used as the basis of the following Lisp functions: (defun sentence () "generates and returns a sentence as a list of atoms" (append (noun-phrase) (verb-phrase))) => SENTENCE (defun noun-phrase () "generates and returns a noun-phrase as a list of atoms" (append (article) (noun))) => NOUN-PHRASE 32

45 Programming Example (continued) (defun verb-phrase () "generates and returns a verb-phrase as a list of atoms" (append (verb) (noun-phrase))) => VERB-PHRASE (defun article () "generates and returns an article as an atom in a list" (one-of '(the a))) => ARTICLE (defun noun () "generates and returns a noun as an atom in a list" (one-of '(man ball woman table))) => NOUN (defun verb () "generates and returns a noun as an atom in a list" (one-of '(hit took saw liked))) => VERB 33

46 (sentence) => (A MAN TOOK THE WOMAN) (sentence) => (THE MAN SAW A MAN) Programming Example (continued) (sentence) => (THE WOMAN TOOK A BALL) (noun-phrase) => (THE WOMAN) (verb-phrase) => (TOOK THE BALL) (noun) => (BALL) (verb) => (LIKED) 34

47 Using the Trace Facility (trace sentence noun-phrase verb-phrase article noun verb) => NIL (sentence) Calling (SENTENCE) Calling (NOUN-PHRASE) Calling (ARTICLE) ARTICLE returned (THE) Calling (NOUN) NOUN returned (MAN) NOUN-PHRASE returned (THE MAN) Calling (VERB-PHRASE) Calling (VERB) VERB returned (HIT) Calling (NOUN-PHRASE) Calling (ARTICLE) ARTICLE returned (THE) Calling (NOUN) NOUN returned (WOMAN) NOUN-PHRASE returned (THE WOMAN) VERB-PHRASE returned (HIT THE WOMAN) SENTENCE returned (THE MAN HIT THE WOMAN) => (THE MAN HIT THE WOMAN) (untrace) => (SENTENCE NOUN-PHRASE VERB-PHRASE ARTICLE NOUN VERB) 35

48 Recursion Dene length in terms of itself: the empty list has length 0 and any other list has a length which is one more than the length of the rest of the list. (defun length (list) (cond ((null list) 0) (BASE) (t (1+ (length (cdr list)))))) (RECURSION: leap of faith) Evaluation of recursive call: Evaluate the argument (cdr list) Bind it to list after old value is saved on stack. Upon return, add 1 to result. Spiral of recursion: unwind when list = NIL (length (a b c)) (length (b c)) (length (c)) (length ())

49 Tail Recursion Note: compiler has to allocate memory for each recursive call. But not true for all recursive calls! In rst def of length: add 1 after returning from recursive call. More ecient to write a \tail-recursive" function: recursive call appears as the last thing the function does (the tail) (defun length (list) (length-aux list 0)) Auxiliary function: uses LEN-SO-FAR as an \accumulator" (defun length-aux (sublist len-so-far) (cond ((null sublist) len-so-far) (t (length-aux (rest sublist) (1+ len-so-far))))) 37

50 Sample Session: Recursion Here's a recursive function called lat?, that takes one argument and returns t if that argument is a list of atoms. (defun lat? (l) "Returns t if the argument is a list of atoms, nil otherwise" (cond ((null l) t) ((atom (car l)) (lat? (cdr l))) (t nil))) => LAT? (lat? '(remember the alamo)) => T (lat? '(did you remember (to floss?))) => NIL (lat? long-list) => T (lat? 12) => > Error: Can't take CAR of 12. > While executing: LAT? > Type Command-. to abort. See the Restarts menu item for further choices. 1 > (defun lat? (l) "Returns t if the argument is a list of atoms, nil otherwise" (cond ((not (listp l)) nil) ((null l) t) ((atom (car l)) (lat? (cdr l))) (t nil))) => LAT? (lat? 12) => NIL 38

51 Sample Session: Recursion (continued) Here's a generalization of double-cons and quadruple-cons we dened previously: (defun multi-cons (one-thing another-thing n) "Returns the result of consing one-thing onto another-thing n times" (cond ((equalp => MULTI-CONS (t (cons one-thing n 0) another-thing) (multi-cons (multi-cons 'hip '(hooray) 5) => (HIP HIP HIP HIP HIP HOORAY) one-thing another-thing (- n 1)))))) The following member? function checks to see if its rst argument occurs in its second: (defun member? "Returns (a lat) t if a occurs in lat, nil otherwise" (cond ((null lat) nil) => MEMBER? (t (or (equalp (car lat) a) (setq five-colleges (member? a (cdr lat)))))) '(amherst umass hampshire smith mount-holyoke)) => (AMHERST UMASS HAMPSHIRE SMITH MOUNT-HOLYOKE) (member? 'hampshire five-colleges) => T (member? 'oberlin five-colleges) => NIL 39

52 MEMBER Recall that Common Lisp includes a function called MEM- BER that does a similar thing. Note, however, that it returns the matching cdr rather than t: (member 'hampshire five-colleges) => (HAMPSHIRE SMITH MOUNT-HOLYOKE) (member 'oberlin five-colleges) => NIL Note that MEMBER compares using EQ, not EQUALP. For example: (member '(nest) '(a hornet in a hornet (nest) is to be avoided)) => NIL (member? '(nest) '(a hornet in a hornet (nest) is to be avoided)) => T We can get MEMBER to match using equalp by providing a keyword argument (details on this another day...) (member '(nest) '(a hornet in a hornet (nest) is to be avoided) :test #'equalp) => ((NEST) IS TO BE AVOIDED) 40

53 A closer look at recursive programming: Wilensky (Common Lispcraft) p. 89:...we have the following components to recursive programming: Breaking down the task at hand into a form that involves simpler versions of the same task. Specifying a way to combine the simpler versions of the task to solve the original problem. Identifying the "grounding" situations in which the task can be accomplished directly. Specifying checks for these grounding cases that will be examined before recursive steps are taken. (defun factorial (n) "returns the factorial of n" (cond ((<= n 1) 1) (t (* n (factorial (- n 1)))))) => FACTORIAL (factorial 5) => 120 (trace factorial) => NIL (factorial 5) Calling (FACTORIAL 5) Calling (FACTORIAL 4) Calling (FACTORIAL 3) Calling (FACTORIAL 2) Calling (FACTORIAL 1) FACTORIAL returned 1 FACTORIAL returned 2 FACTORIAL returned 6 FACTORIAL returned 24 FACTORIAL returned 120 =>

54 Factorial and Length Revisited Another version of Factorial: (defun factorial (n) "returns the factorial of n" (cond ((zerop n) 1) (t (* n (factorial (- n 1)))))) => FACTORIAL (factorial 5) => 120 Using IF we can write a simpler version of factorial: (defun factorial (n) "returns the factorial of n" (if (zerop n) 1 (* n (factorial (- n 1))))) => FACTORIAL (factorial 5) => 120 Here's a recursive length function: (defun my-length (list) "returns the length of list" (if (null list) 0 (+ 1 (my-length (cdr list))))) => MY-LENGTH (my-length '(let it snow let it snow let it AAAARRRRRGGGGGHHHH!!!!)) => 9 42

55 Iteration: DOTIMES Sometimes iteration seems more natural. Common Lisp provides many iteration constructs. DOTIMES (var countform [resultform]) {declaration}* {tag statement}* [Macro] Executes forms countform times. On successive executions, var is bound to the integers between zero and countform. Upon completion, resultform is evaluated, and the value is returned. If resultform is omitted, the result is nil. (dotimes (n 20 'spumoni) (print n)) => SPUMONI 43

56 Iteration: DOTIMES (continued) Here was our recursive function multicons: (defun multi-cons (one-thing another-thing n) "Returns the result of consing one-thing onto another-thing n times" (cond ((equalp n 0) another-thing) (t (cons one-thing (multi-cons one-thing another-thing (- n 1)))))) => MULTI-CONS (multi-cons 'hip '(hooray) 5) => (HIP HIP HIP HIP HIP HOORAY) Here's a version using dotimes: (defun multi-cons (one-thing another-thing n) "Returns the result of consing one-thing onto another-thing n times" (dotimes (count n) (setq another-thing (cons one-thing another-thing))) another-thing) => MULTI-CONS (multi-cons 'hip '(hooray) 5) => (HIP HIP HIP HIP HIP HOORAY) 44

57 Iteration: DOLIST DOLIST (var listform [resultform]) {declaration}* {tag statement}* [Macro] Evaluates listform, which produces a list, and executes the body once for every element in the list. On each iteration, var is bound to successive elements of the list. Upon completion, resultform is evaluated, and the value is returned. If resultform is omitted, the result is nil. (defun greet (people) "prints greetings for all of the people listed." (dolist (person people) (print (append '(so nice to see you) (list person))))) => GREET (setq guests '(sally booboo mr-pajamas ms-potato-head)) => (SALLY BOOBOO MR-PAJAMAS MS-POTATO-HEAD) (greet guests) (SO NICE TO SEE YOU SALLY) (SO NICE TO SEE YOU BOOBOO) (SO NICE TO SEE YOU MR-PAJAMAS) (SO NICE TO SEE YOU MS-POTATO-HEAD) => NIL 45

58 #' Funny #' notation (sharp-quote): maps name of function to function itself. Equivalent to FUNCTION. Always use this when using mapcar, apply, funcall, lambda expressions keywords (e.g., :TEST). Note: only functions may be quoted (not macros or special forms). More ecient means something to compiler: go to compiled code, not through symbol to nd function defn. Analogous to quote. Use any time a function is speci- ed. Mapcar: Expects an n-ary fn as 2st arg, followed by n lists. It applies the fn to the arg list obtained by collecting the rst elt of each list. (mapcar #'1+ '(5 10 7))! (6 11 8) (mapcar (function 1+) '(5 10 7))! (6 11 8) (mapcar #'cons '(a b c) '(1 2 3))! ((A.1)(B. 2) (C. 3)) (mapcar #'print '(a b c))! (A B C) Note: last case also has side eect of printing A, B, and C. Avoid consing up a whole new list by using Mapc: (mapc #'print '(a b c))! (A B C) [This prints A, B, and C, but then returns the second arg, NOT a new list.] 1

59 Apply, Funcall, Eval Following forms equivalent: (+1234) (funcall #' ) (apply #'+ '( )) (apply #'+ 1 2 '(3 4)) (eval '( )) Funcall: great to use if we don't know function name in advance (funcall <fn> arg1 arg2...) Applies to arguments, not in a list. But what if we don't know the no. of args in advance? Apply: same idea, but don't need to know no. of args (apply <fn> arg1 arg2... arglist) Applies to arguments last arg MUST be a list Eval: in general we can use funcall and apply. 2

60 Lambda expressions: apply, funcall Lambda expressions specify a function without a name. (Ah hah! so now we see how apply/funcall will be used.) Lambda is most primitive way to specify fn has its roots in lambda calculus of Church (lambda (parameters...) body...) A lambda expr is a nonatomic name for a fn, just as append is an atomic name for a built-in. Use the #' notation. Example: (funcall #'(lambda (x) (+ x x)) 2)! 4 (apply #'(lambda (x) (+ x x)) '(2))! 4(wasteful) (mapcar #'(lambda (x) (+ x x)) '( ))! '( ) *** Programmers who are used to other langs sometimes fail to see the point of lambda expressions. Why are they useful? (1) It's a pain to think up names and to clutter up a program with lots of functions that are only used very locally (2) MORE IMPORTANT: can create new functions at run time. Note: cannot give a lambda expr to lisp to eval \lambda" not a function! But can use it as car of a list: ((lambda (x)(+xx))2)! 4. (I don't use this though.) Note: Defun is a macro that expands out to lambda so there's really only one way to specify a fn, not two! (symbol-function <fn>) returns lambda expression. 3

61 IF vs. COND (slide 21 of previous lecture) The IF special form is a special case of COND: IF testform thenform [elseform] Evaluates testform. If the result is true, evaluates thenform and returns the result if the result is nil, evaluates elseform and returns the result. (if (> ) 'sure-is => SURE-IS 'sure-aint) (if (member 'bog '(blig blog bog bumper)) (* 99 99) (sqrt -1)) => 9801 (if (member 'fog '(blig blog bog bumper)) (* 99 99) (sqrt -1)) => #c(0 1) Note that the thenform and the elseform are both restricted to being single forms. In contrast, you can specify any numberofforms in a cond clause: (setq temperature 8) => 8 (cond ((< temperature 32) (print '(yowch -- it is cold!)) (print (t '(i will play god and change that!)) (setq temperature 78)) (print '(well i guess it is not so bad)) (print '(where do you think (YOWCH -- IT IS COLD!) we are? hawaii?)))) (I WILL PLAY GOD AND CHANGE THAT!) => 78 2

62 PROGN If you want multiple formsinanifyou can use a PROGN: Evaluates each form in order, left to right. The values of all forms but the last are discarded the value of the last form is returned. (if (< temperature 32) (progn (print '(yowch -- it is cold!)) (print (progn (print '(i will play god and change that!)) (setq temperature 78)) '(well i guess it is not so bad)) (print '(where do you think we are? hawaii?)))) (WELL I GUESS IT IS NOT SO BAD) (WHERE DO YOU THINK WE ARE? HAWAII?) => (WHERE DO YOU THINK WE ARE? HAWAII?) 3

63 Sample Session: COND (setq x 23) => 23 (cond ((equalp x 1) '(it was one)) ((equalp x 2) '(it was two)) (t '(it was not one or two))) => (IT WAS NOT ONE OR TWO) (setq x 2) => 2 (cond ((equalp x 1) '(it was one)) ((equalp x 2) '(it was two)) (t '(it was not one or two))) => (IT WAS TWO) 4

64 Sample Session: Operations on Lists (slide 30 of previous lecture) The NTH function returns an element of a list by number (setq animals '(giraffe dog dinosaur bug big-bug big-hairy-bug)) => (GIRAFFE DOG DINOSAUR BUG BIG-BUG BIG-HAIRY-BUG) (nth 0 animals) => GIRAFFE (nth 1 animals) => DOG (nth 2 animals) => DINOSAUR (nth 3 animals) => BUG (nth 4 animals) => BIG-BUG (nth 5 animals) => BIG-HAIRY-BUG (nth 6 animals) => NIL The LENGTH function returns the number of elements in a list (length animals) => 6 (length '(the (deeper (you (go (the (nuller (you (get))))))))) => 2 5

65 Sample Session: Operations on Lists (continued) Here's a function to return a random element of a list (defun random-elt (choices) "returns one element of the list of choices at random" (nth (random (length choices)) choices)) => RANDOM-ELT (random-elt animals) => BUG (random-elt animals) => BIG-BUG This returns a random element as a singleton list (defun one-of (set) "picks one element of the set and returns it in a list" (list (random-elt set))) => ONE-OF (one-of '(how are you doing today?)) => (YOU) 6

66 Sample Session: Recursion Revisited (slide 39 of previous lecture) Here's a recursive function called lat?, that takes one argument and returns t if that argument is a list of atoms. (defun lat? (l) "Returns t if the argument is a list of atoms, nil otherwise" (cond ((null l) t) ((atom (car l)) (lat? (cdr l))) (t nil))) => LAT? (lat? '(remember the alamo)) => T (lat? '(did you remember (to floss?))) => NIL (lat? long-list) => T (lat? 12) => > Error: Can't take CAR of 12. > While executing: LAT? > Type Command-. to abort. See the Restarts menu item for further choices. 1 > (defun lat? (l) "Returns t if the argument is a list of atoms, nil otherwise" (cond ((not (listp l)) nil) ((null l) t) ((atom (car l)) (lat? (cdr l))) (t nil))) => LAT? (lat? 12) => NIL 7

67 Sample Session: Recursion (continued) Recall the double-cons and quadruple-cons functions (de- ned in previous lecture): (defun double-cons (one-thing another-thing) "Returns the result of consing one-thing onto another-thing twice" (cons one-thing (cons one-thing another-thing))) => DOUBLE-CONS (double-cons => (HIP HIP HOORAY) 'hip '(hooray)) (defun quadruple-cons (one-thing another-thing) "Returns the result of consing one-thing onto another-thing 4x" (double-cons one-thing (double-cons one-thing another-thing))) => QUADRUPLE-CONS (quadruple-cons => (UM UM UM UM HUH?) 'um '(huh?)) Here's a generalization of double-cons and quadruple-cons we dened previously: (defun multi-cons (one-thing another-thing n) "Returns the result of consing one-thing onto another-thing n times" (cond ((equalp => MULTI-CONS (t (cons one-thing n 0) another-thing) (multi-cons (multi-cons 'hip '(hooray) 5) => (HIP HIP HIP HIP HIP HOORAY) one-thing another-thing (- n 1)))))) 8

68 MEMBER The following member? function checks to see if its rst argument occurs in its second: (defun member? "Returns (a lat) t if a occurs in lat, nil otherwise" (cond ((null lat) nil) => MEMBER? (t (or (equalp (car lat) a) (setq five-colleges (member? a (cdr lat)))))) '(amherst umass hampshire smith mount-holyoke)) => (AMHERST UMASS HAMPSHIRE SMITH MOUNT-HOLYOKE) (member? 'hampshire five-colleges) => T (member? 'oberlin five-colleges) => NIL Recall that Common Lisp includes a function called MEM- BER that does a similar thing. Note, however, that it returns the matching cdr rather than t: (member 'hampshire five-colleges) => (HAMPSHIRE SMITH MOUNT-HOLYOKE) (member 'oberlin five-colleges) => NIL Note that MEMBER compares using EQ, not EQUALP. For example: (member '(nest) '(a hornet in a hornet (nest) is to be avoided)) => NIL (member? '(nest) '(a hornet in a hornet (nest) is to be avoided)) => T We can get MEMBER to match using equalp by providing a keyword argument: (member '(nest) '(a hornet in a hornet (nest) is to be avoided) :test #'equalp) => ((NEST) IS TO BE AVOIDED) 9

69 A closer look at recursive programming (slide 41 of previous lecture) Wilensky (Common Lispcraft) p. 89:...we have the following components to recursive programming: Breaking down the task at hand into a form that involves simpler versions of the same task. Specifying a way to combine the simpler versions of the task to solve the original problem. Identifying the "grounding" situations in which the task can be accomplished directly. Specifying checks for these grounding cases that will be examined before recursive steps are taken. (defun factorial (n) "returns the factorial of n" (cond ((<= n 1) 1) (t (* n (factorial (- n 1)))))) => FACTORIAL (factorial 5) => 120 (trace factorial) => NIL (factorial 5) Calling (FACTORIAL 5) Calling (FACTORIAL 4) Calling (FACTORIAL 3) Calling (FACTORIAL 2) Calling (FACTORIAL 1) FACTORIAL returned 1 FACTORIAL returned 2 FACTORIAL returned 6 FACTORIAL returned 24 FACTORIAL returned 120 =>

70 Factorial and Length Revisited (slide 42 of previous lecture) Another version of Factorial: (defun factorial (n) "returns the factorial of n" (cond ((zerop n) 1) => FACTORIAL (factorial 5) => 120 (t (* n (factorial (- n 1)))))) Using IF we can write a simpler version of factorial: (defun factorial (n) "returns the factorial of n" (if (zerop n) 1 (* n (factorial (- n 1))))) => FACTORIAL (factorial 5) => 120 Here's a recursive length function: (defun my-length (list) "returns the length of list" (if (null list) 0 (+ 1 (my-length (cdr list))))) => MY-LENGTH (my-length '(let it snow let it snow let it AAAARRRRRGGGGGHHHH!!!!)) => 9 11

71 Iteration: DOTIMES (slide 43 of previous lecture) Sometimes iteration seems more natural. Common Lisp provides many iteration constructs. We talked about DOLIST last time. Another is DOTIMES. DOTIMES (var countform [resultform]) {declaration}* {tag statement}* [Macro] Executes forms countform times. On successive executions, var is bound to the integers between zero and countform. Upon completion, resultform is evaluated, and the value is returned. If resultform is omitted, the result is nil. (dotimes (n 20 'spumoni) (print n)) => SPUMONI 12

72 Iteration: DOTIMES (continued) Here was our recursive function multicons: (defun multi-cons (one-thing another-thing n) "Returns the result of consing one-thing onto another-thing n times" (cond ((equalp n 0) another-thing) (t (cons one-thing (multi-cons one-thing another-thing (- n 1)))))) => MULTI-CONS (multi-cons 'hip '(hooray) 5) => (HIP HIP HIP HIP HIP HOORAY) Here's a version using dotimes: (defun multi-cons (one-thing another-thing n) "Returns the result of consing one-thing onto another-thing n times" (dotimes (count n) (setq another-thing (cons one-thing another-thing))) another-thing) => MULTI-CONS (multi-cons 'hip '(hooray) 5) => (HIP HIP HIP HIP HIP HOORAY) 13

73 Keyword arguments: remove So what are all these keywords? Let's look at remove: (remove 1 '( )) => ( ) (remove 1 '( ) :key #'abs) => ( ) (remove 1 '( ) :test #'<) => ( ) (remove 1 '( ) :start 4) => ( ) 14

74 Global Variables Global, dynamically scoped variables can be created with defvar ordefparameter DEFVAR [Macro] variable-name &optional initial-value documentation DEFVAR proclaims variable-name to be a special variable, optionally sets it to the value of initial-value, and returns variable-name. If initial-value is given, variable-name is initialized to the result of evaluating it unless variable-name already has a value. If initial-name is not used, it is not evaluated. The macro defvar only has an eect the rst time it is called on a symbol. Documentation may bepro- vided as a string. DEFPARAMETER variable-name initial-value &optional documentation [Macro] DEFPARAMETER proclaims variable-name to be a special variable, sets it to the value of evaluating initial-value, a form, and returns variable-name. Documentation may be provided as a string. Globals are conventionally written with surrounding * characters: (defvar *world-state* '((clear block-a) (on block-a table))) (defparameter *depth-limit* 10 "The maximum depth to which we will search") Note: Subsequent defvars for a previously defvar'd variable are ignored. Subsequent defparameters act as setq's. 15

75 Defparameter, defvar, defconstant (DEF var-name init-val) DEFPARAMETER: denes param, i.e., a var that does not change over course of computation, but that might change when we think of new things to add. A change to a param is a change TO the pgm. DEFVAR: routinely changed during the course of running the program. A change to a param is a change BY the pgm. DEFCONSTANT: declare a symbol that will ALWAYS stand for aparticular value. (Compiler optimizes might expand out in a macro, for example, and an error will result at RT if a val is assigned.) Important note: There is a dierence between DEFPARAMETER and DEFVAR: If global initialized using DEFPARAMETER in a le, then each time le is loaded, the global will be reset to the initial value. If global initialized using DEFVAR in a le, then ONLY THE FIRST TIME the le is loaded will the global set to the initial value (not on subsequent times). Why is this the case? DEFVAR doesn't reinitialize a var because it assumes this val is in ux and may change many times over it takes the initial val as the TRUE initial val and won't reinitialize w/o an explicit SETF. DEFPARAMETER is dierent it assumes that if you're giving it an initial value that will not be changed by the program. So it WILL reinitialize each time the le is loaded. 16

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

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

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

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

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

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

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

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

CSCI337 Organisation of Programming Languages LISP

CSCI337 Organisation of Programming Languages LISP Organisation of Programming Languages LISP 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 8 8 8 8 8 o 8 8 I \ `+' / I 8 8 8 8 8 8 \ `-+-' / 8 8 8 ooooo

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

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

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

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 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

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

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

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

6.001 Notes: Section 8.1

6.001 Notes: Section 8.1 6.001 Notes: Section 8.1 Slide 8.1.1 In this lecture we are going to introduce a new data type, specifically to deal with symbols. This may sound a bit odd, but if you step back, you may realize that everything

More information

6.001 Notes: Section 15.1

6.001 Notes: Section 15.1 6.001 Notes: Section 15.1 Slide 15.1.1 Our goal over the next few lectures is to build an interpreter, which in a very basic sense is the ultimate in programming, since doing so will allow us to define

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

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

Debugging in LISP. trace causes a trace to be printed for a function when it is called

Debugging in LISP. trace causes a trace to be printed for a function when it is called trace causes a trace to be printed for a function when it is called ;;; a function that works like reverse (defun rev (list) (cons (first (last list)) (rev (butlast list)))) USER: (trace rev) ; note trace

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

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: 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

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

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

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

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

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

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

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

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

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

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

Recursion & Iteration

Recursion & Iteration Recursion & Iteration York University Department of Computer Science and Engineering 1 Overview Recursion Examples Iteration Examples Iteration vs. Recursion Example [ref.: Chap 5,6 Wilensky] 2 Recursion

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

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

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

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

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

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

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

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

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

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

FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 4. LISP: PROMĚNNÉ, DALŠÍ VLASTNOSTI FUNKCÍ, BLOKY, MAPOVACÍ FUNKCIONÁLY, ITERAČNÍ CYKLY,

FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 4. LISP: PROMĚNNÉ, DALŠÍ VLASTNOSTI FUNKCÍ, BLOKY, MAPOVACÍ FUNKCIONÁLY, ITERAČNÍ CYKLY, FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 4. LISP: PROMĚNNÉ, DALŠÍ VLASTNOSTI FUNKCÍ, BLOKY, MAPOVACÍ FUNKCIONÁLY, ITERAČNÍ CYKLY, 2011 Jan Janoušek MI-FLP Evropský sociální fond Praha & EU: Investujeme do vaší

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

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

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 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

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

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

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

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

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

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

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 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

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

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

6.184 Lecture 4. Interpretation. Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson 6.184 Lecture 4 Interpretation Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson 1 Interpretation Parts of an interpreter Arithmetic calculator

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

6.001 Notes: Section 6.1

6.001 Notes: Section 6.1 6.001 Notes: Section 6.1 Slide 6.1.1 When we first starting talking about Scheme expressions, you may recall we said that (almost) every Scheme expression had three components, a syntax (legal ways of

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

Typed Racket: Racket with Static Types

Typed Racket: Racket with Static Types Typed Racket: Racket with Static Types Version 5.0.2 Sam Tobin-Hochstadt November 6, 2010 Typed Racket is a family of languages, each of which enforce that programs written in the language obey a type

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

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

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

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

The Typed Racket Guide

The Typed Racket Guide The Typed Racket Guide Version 5.3.6 Sam Tobin-Hochstadt and Vincent St-Amour August 9, 2013 Typed Racket is a family of languages, each of which enforce

More information

Department of Computer and information Science Norwegian University of Science and Technology

Department of Computer and information Science Norwegian University of Science and Technology Department of Computer and information Science Norwegian University of Science and Technology http://www.idi.ntnu.no/ A Crash Course in LISP MNFIT272 2002 Anders Kofod-Petersen anderpe@idi.ntnu.no Introduction

More information

Allegro CL Certification Program

Allegro CL Certification Program Allegro CL Certification Program Lisp Programming Series Level I Presented by 1 About David Margolies Manager, Documentation, Franz Inc Been working with Lisp since 1984 dm@franz.com 2 About Franz Inc.

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 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

A Small Interpreted Language

A Small Interpreted Language A Small Interpreted Language What would you need to build a small computing language based on mathematical principles? The language should be simple, Turing equivalent (i.e.: it can compute anything that

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

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

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

6.001: Structure and Interpretation of Computer Programs

6.001: Structure and Interpretation of Computer Programs 6.001: Structure and Interpretation of Computer Programs Symbols Quotation Relevant details of the reader Example of using symbols Alists Differentiation Data Types in Lisp/Scheme Conventional Numbers

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

CS61A Midterm 2 Review (v1.1)

CS61A Midterm 2 Review (v1.1) Spring 2006 1 CS61A Midterm 2 Review (v1.1) Basic Info Your login: Your section number: Your TA s name: Midterm 2 is going to be held on Tuesday 7-9p, at 1 Pimentel. What will Scheme print? What will the

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

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

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

Announcements. The current topic: Scheme. Review: BST functions. Review: Representing trees in Scheme. Reminder: Lab 2 is due on Monday at 10:30 am.

Announcements. The current topic: Scheme. Review: BST functions. Review: Representing trees in Scheme. Reminder: Lab 2 is due on Monday at 10:30 am. The current topic: Scheme! Introduction! Object-oriented programming: Python Functional programming: Scheme! Introduction! Numeric operators, REPL, quotes, functions, conditionals! Function examples, helper

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

Robot Programming with Lisp

Robot Programming with Lisp 2. Imperative Programming Institute for Artificial University of Bremen Lisp the Language LISP LISt Processing language 2 Lisp the Language LISP LISt Processing language (LISP Lots of Irritating Superfluous

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

Defining Program Syntax. Chapter Two Modern Programming Languages, 2nd ed. 1

Defining Program Syntax. Chapter Two Modern Programming Languages, 2nd ed. 1 Defining Program Syntax Chapter Two Modern Programming Languages, 2nd ed. 1 Syntax And Semantics Programming language syntax: how programs look, their form and structure Syntax is defined using a kind

More information

PROFESSOR: Last time, we took a look at an explicit control evaluator for Lisp, and that bridged the gap between

PROFESSOR: Last time, we took a look at an explicit control evaluator for Lisp, and that bridged the gap between MITOCW Lecture 10A [MUSIC PLAYING] PROFESSOR: Last time, we took a look at an explicit control evaluator for Lisp, and that bridged the gap between all these high-level languages like Lisp and the query

More information

6.037 Lecture 4. Interpretation. What is an interpreter? Why do we need an interpreter? Stages of an interpreter. Role of each part of the interpreter

6.037 Lecture 4. Interpretation. What is an interpreter? Why do we need an interpreter? Stages of an interpreter. Role of each part of the interpreter 6.037 Lecture 4 Interpretation Interpretation Parts of an interpreter Meta-circular Evaluator (Scheme-in-scheme!) A slight variation: dynamic scoping Original material by Eric Grimson Tweaked by Zev Benjamin,

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

6.001 Notes: Section 31.1

6.001 Notes: Section 31.1 6.001 Notes: Section 31.1 Slide 31.1.1 In previous lectures we have seen a number of important themes, which relate to designing code for complex systems. One was the idea of proof by induction, meaning

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

Week 2: The Clojure Language. Background Basic structure A few of the most useful facilities. A modernized Lisp. An insider's opinion

Week 2: The Clojure Language. Background Basic structure A few of the most useful facilities. A modernized Lisp. An insider's opinion Week 2: The Clojure Language Background Basic structure A few of the most useful facilities A modernized Lisp Review of Lisp's origins and development Why did Lisp need to be modernized? Relationship to

More information

Ruby: Introduction, Basics

Ruby: Introduction, Basics Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 3 Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie

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

Lecture 09: Data Abstraction ++ Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree.

Lecture 09: Data Abstraction ++ Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree. Lecture 09: Data Abstraction ++ Parsing Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree. program text Parser AST Processor Compilers (and some interpreters)

More information