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

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

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

Modern Programming Languages. Lecture LISP Programming Language An Introduction

Common LISP-Introduction

Common LISP Tutorial 1 (Basic)

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

Lecture Notes on Lisp A Brief Introduction

Common Lisp. Blake McBride

CSCI337 Organisation of Programming Languages LISP

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

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

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

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

Functional Programming. Pure Functional Languages

Functional programming with Common Lisp

Imperative, OO and Functional Languages A C program is

Functional Programming. Big Picture. Design of Programming Languages

Functional Programming. Pure Functional Languages

6.001 Notes: Section 8.1

6.001 Notes: Section 15.1

Introduction to Scheme

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

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

User-defined Functions. Conditional Expressions in Scheme

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

Scheme: Expressions & Procedures

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

Artificial Intelligence Programming

CSC 533: Programming Languages. Spring 2015

FP Foundations, Scheme

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

Functional Programming. Pure Functional Programming

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

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

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


Recursion & Iteration

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

Lecture #2 Kenneth W. Flynn RPI CS

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

Lisp Basic Example Test Questions

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

Allegro CL Certification Program

CS 314 Principles of Programming Languages

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

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

Scheme Quick Reference

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

Scheme Quick Reference

A little bit of Lisp

LECTURE 16. Functional Programming

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

A Brief Introduction to Scheme (II)

Organization of Programming Languages CS3200/5200N. Lecture 11

SCHEME AND CALCULATOR 5b

Functions, Conditionals & Predicates

Notes on Higher Order Programming in Scheme. by Alexander Stepanov

Lambda Calculus see notes on Lambda Calculus

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

A Genetic Algorithm Implementation

Functional Programming

CS 360 Programming Languages Interpreters

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

INF4820. Common Lisp: Closures and Macros

6.001 Notes: Section 6.1

A Quick Introduction to Common Lisp

Typed Racket: Racket with Static Types

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

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

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

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

The Typed Racket Guide

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

Allegro CL Certification Program

Lisp. Versions of LISP

Functional Programming Languages (FPL)

A Small Interpreted Language

Documentation for LISP in BASIC

CSCC24 Functional Programming Scheme Part 2

Announcements. Today s Menu

6.001: Structure and Interpretation of Computer Programs

CPS 506 Comparative Programming Languages. Programming Language Paradigm

CS61A Midterm 2 Review (v1.1)

Chapter 15. Functional Programming Languages

Scheme: Strings Scheme: I/O

Putting the fun in functional programming

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

Chapter 1. Fundamentals of Higher Order Programming

Robot Programming with Lisp

Introduction to Lisp

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

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

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

15 Unification and Embedded Languages in Lisp

6.001 Notes: Section 31.1

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

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

Ruby: Introduction, Basics

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

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

Transcription:

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

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

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

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

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

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

Atoms and Lists Atoms: atom turkey 1492 3turkeys *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

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

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

Sample Session Fire up Lisp... (+ 1 1) => 2 (* 23 13) => 299 (+ 1 (* 23 13)) => 300 (+ (* 2 2) (- 10 9)) => 5 (* 2 2 2 2) => 16 (sqrt (* 2 2 2 2)) => 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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

(null 'fig-tree) => NIL (null '(bismark)) => NIL (null '()) => T (null ()) => T (null nil) => T (atom 'eggplant) => T (atom 99) => T (atom 3.141592) => 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

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 (< 1 2 3 4 5 6 7 8 9) => T (< 1 2 3 4 5 6 7 8 7) => NIL 15

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

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

Sample Session: Equality (equalp 'foot 'foot) => T (equalp 'nose 'ear) => NIL (equalp (+ 22 33 44) (* 33 3)) => T (setq long-list '(1 2 3 4 can I show you out the door?)) => (1 2 3 4 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

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 12... E 2 N (when C E 1 E 2 ) C 1 Y E 11 E 12... 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

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

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 (> 100 23) '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

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

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

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

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

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

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 99 100) => 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 99 100) => 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

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)) => (1 1 1 1) (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

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

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

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

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

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

(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

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

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 ()) 0 1 2 3 36

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

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

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

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

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 => 120 41

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

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)) 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 => SPUMONI 43

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

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

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

Apply, Funcall, Eval Following forms equivalent: (+1234) (funcall #'+ 1 2 3 4) (apply #'+ '(1 2 3 4)) (apply #'+ 1 2 '(3 4)) (eval '(+ 1 2 3 4)) 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

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)) '(1 2 3 4 5))! '(2 4 6 8 10) *** 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

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 (> 100 23) '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

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

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

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

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

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

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

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

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 => 120 10

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

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)) 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 => SPUMONI 12

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

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

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

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