CSCI 2210: Programming in Lisp. Progn. Block. CSCI Programming in Lisp; Instructor: Alok Mehta 1. ANSI Common Lisp, Chapters 5-10

Size: px
Start display at page:

Download "CSCI 2210: Programming in Lisp. Progn. Block. CSCI Programming in Lisp; Instructor: Alok Mehta 1. ANSI Common Lisp, Chapters 5-10"

Transcription

1 CSCI 2210: Programming in Lisp ANSI Common Lisp, Chapters 5-10 CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 1 Progn Progn Creates a block of code Expressions in body are evaluated Value of last is returned (if (< x 0) (progn (format t "X is less than zero ") (format t "and more than one statement ") (format t "needs to be executed in the IF") (- x) ) ) Prog1 Same as progn, except value of first expression is returned CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 2 Block Like a progn with A name An "emergency exit" return-from - Returns from a named block return - Returns from a block named NIL Examples > (block head (format t "Here we go") (return-from head 'idea) (format t "We'll never see this")) Here we go. IDEA > (block nil (return 27)) 27 CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 3 CSCI Programming in Lisp; Instructor: Alok Mehta 1

2 Implicit use of Blocks Some Lisp constructs implicitly use blocks All iteration constructs use a block named NIL (note return) > (dolist (x '(a b c d e)) (format t "~A " x) (if (eql x 'c) (return 'done))) A B C DONE Defun uses a block with same name as the function > (defun foo () (return-from foo 27)) CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 4 Iteration DOTIMES (Review) (dotimes (<counter> <upper-bound> <final-result>) <body>) Example (dotimes (i 5) (print i)) ;; prints DOLIST (dolist (<element> <list-of-elements> <final-result>) <body>) Example (dolist (elem '(a b c d)) (print elem)) ;; prints a b c d CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 5 Example of DOLIST Given a list of ages of people, how many adults? List of ages > (setf ages '( )) Adult defined as: >= 21 years old > (defun adultp (age) (>= age 21)) Using Count-if (defun count-adult (ages) (count-if #'adultp ages)) Using dolist (defun count-adult (ages &aux (nadult 0)) (dolist (age ages nadult) (if (adultp age) (setf nadult (+ 1 nadult))))) CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 6 CSCI Programming in Lisp; Instructor: Alok Mehta 2

3 Example (cont.) Get the ages of the first two adults (defun first-two-adults (ages &aux (nadult 0) (adults nil)) (dolist (age ages) (if (adultp age) (progn (setf nadult (+ nadult 1)) (push age adults) (if (= nadult 2) (return adults)))))) Notes PROGN (and PROG1) are like C/C++ Blocks { } > (prog1 (setf a 'x) (setf b 'y) (setf c 'z)) X > (progn (setf a 'x) (setf b 'y) (setf c 'z)) Z RETURN exits the DOLIST block Note: does not necessarily return from the procedure! Takes an optional return value CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 7 DO DO is more general than DOLIST or DOTIMES Example (defun do-expt (m n) ;; Return M^N (do ((result 1) ;; Bind variable Result to 1 (exponent n)) ;; Bind variable Exponent to N ((zerop exponent) result) ;; test and return value (setf result (* m result)) ;; Body (setf exponent (- exponent 1)) ;; Body Equivalent C/C++ definition int do_expt (int m, int n) { int result, exponent; for (result=1,exponent=n; (exponent!= 0); ) { result = m * result; exponent = exponent - 1; } return result; } CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 8 DO Template Full DO Template (There is also a DO*) (DO ( (<p1> <i1> <u1>) (<p2> <i2> <u2>) (<pn> <in> <un>) ) ( <term-test> <a1> <a2> <an> <result> ) <body> ) Rough equivalent in C/C++ for ( <p1>=<i1>, <p2>=<i2>,,<pn>=<in>; //Note: Lisp=parallel!(<term-test>); // C/C++ has a continuation-test <p1>=<u1>, <p2>=<u2>,,<pn>=<un>) { <body> } <a1>; <a2>; ; <an>; <result>; // Note: (DO ) in Lisp evaluates to <result> // Note: <p1>,<p2>,,<pn> are now restored to original values CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 9 CSCI Programming in Lisp; Instructor: Alok Mehta 3

4 Do-expt, Loop Here is another (equivalent) definition of do-expt (defun do-expt (m n) (do ((result 1 (* m result)) (exponent n (- exponent 1))) ((zerop exponent) result) ;; Note that there is no body! )) Loop An infinite loop, terminated only by a (return) (loop (print '(Say uncle)) (if (equal (read) 'uncle) (return))) CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 10 Multiple Values We said each lisp expression returns a value Actually, can return zero or more values (i.e. multiple values) > (round 7.6) ; Round returns two values > (setf a (round 7.6)) 8 ; Setf expects only one value, so it takes the first (8) > a 8 How can you get all values? > (multiple-value-list (round 7.6)) (8-0.4) > (multiple-value-setq (intpart dif) (round 7.6)) 8 > intpart 8 > dif -0.4 CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 11 Generating Multiple Values How? Use values > (values 1 2 3) ; Generates 3 return values > (defun uncons (alist) (values (first alist) (rest alist))) UNCONS > (uncons '(A B C)) A (B C) > (format t "Hello World") "Hello World" NIL > (defun format-without-return (out str &rest args) (apply #'format out str args) (values)) ; A function with no return value! FORMAT-WITHOUT-RETURN > (format-without-return t "Hello") Hello > CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 12 CSCI Programming in Lisp; Instructor: Alok Mehta 4

5 Functions about functions FBOUNDP - Is a symbol the name of a function? > (fboundp '+) T SYMBOL-FUNCTION - returns function > (symbol-function '+) #<Compiled-Function + 17B4E> > (setf (symbol-function 'sqr) #'(lambda (x) (* x x))) #<Interpreted-Function SQR> > (defun sqr (x) (* x x)) ; this is equivalent to above SQR Defun and symbol-function define global functions Local functions can be defined using LABELS > (defun add3 (x) (labels ((add1 (x) (+ x 1)) (add2 (x) (+ x 2))) (add1 (add2 x)))) CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 13 Closures Want a function that can save some values for future access/update Can use global variables for this > (setf *number-of-hits* 0) ; Global variable 0 > (defun increment-hits () (incf *number-of-hits*)) INCREMENT-HITS > (increment-hits) 1 > (increment-hits) 2 But, what if someone clobbers the variable? > (setf *number-of-hits* "This variable is now a string") "This variable is now a string" > (increment-hits) Error: '*number-of-hits*' is not of the expected type: NUMBER Want something like "static" variables in C/C++. CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 14 Closures (continued) One use of closures is to implement 'static' variables safely Closure -- Combination of a function and environment Environment can include values of variables > (let ((number-of-hits 0)) (defun increment-hits () (incf number-of-hits))) INCREMENT-HITS number-of-hits is a free variable It is a lexical variable (has scope) A function that refers to a free lexical variable is called a closure Multiple functions can share the same environment > (let ((number-of-hits 0)) (defun increment-hits() (incf number-of-hits)) (defun reset-hit-counter() (setf number-of-hits 0)) CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 15 CSCI Programming in Lisp; Instructor: Alok Mehta 5

6 Closures (cont) Example 1 > (defun make-adder (n) ; returns function to add n to x #'(lambda (x) (+ x n))) > (setf add3 (make-adder 3)) ; returns function to add 3 #<Interpreted function C0EBF6> > (funcall add3 2) ; Call function add3 with argument 2 5 > (setf (symbol-function 'add3-b) (make-adder 3)) > (add3-b 5) 8 Example 2 - Returns an "opposite" function > (defun our-complement (f) #(lambda (&rest args) (not (apply f args)))) > (mapcar (our-complement #'oddp) '( )) (NIL T NIL T) Tip of the iceberg in terms of possibilities CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 16 Trace Format (trace <procedure-name>) Example > (defun factorial (x) (if (<= x 1) 1 (factorial (- x 1)))) > (trace factorial) Causes entry, exit, parameter, and return values to be printed For EACH procedure being traced > (factorial 3) ; 1> FACTORIAL called with arg: 3 ; 2> FACTORIAL called with arg: 2 ; 3> FACTORIAL called with arg: 1 ; 3< FACTORIAL returns value: 1 ; 2< FACTORIAL returns value: 2 ; 1< FACTORIAL returns value: 6 6 Untrace stops tracing a procedure: (untrace <procedure-name>) CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 17 Print, Read Print Example > (print '(A B)) Evaluates a single argument Can be a constant (ex. 100), a variable (x), or any single expression Prints its value on a new line Returns the value printed Read - reads a single expression Example: > (read)20 23 (A B) C 20 ;; Note: Only the 20 is read; rest is ignored > (progn (print 'Enter-temperature) (read)) Enter-temperature CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 18 CSCI Programming in Lisp; Instructor: Alok Mehta 6

7 Format Format Allows more elegant printing > (progn (print "Enter temperature: ") (read)) "Enter temperature: " > (progn (format t "~%Enter temperature: ") (read)) Enter temperature: The second parameter (t) is the output buffer (T=stdout) The character ~ signifies that a control character follows The character % signifies a newline (Lisp: ~% C: \n ) The characters ~a tells Lisp to substitute the next value printf ("The value is ( %d, %d )", x, y); /* A C stmt */ > (format t "The value is ( ~a, ~a )" x y) ;; Lisp way > (format t "The value is ( ~10a, ~a )" x y) ; Can get fancy CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 19 Streams Write output to a file (e.g. knowledge base) Prototype of with-open-file (with-open-file (<stream name> <file specification> :direction <:input or :output>) ) Example > (setf fact-database '((It is raining) (It is pouring) (The old man is snoring))) > (with-open-file (my-file myfile.lsp :direction :output) (print fact-database my-file)) CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 20 My-Trace-Load Redefine the built-in Lisp Load function Example of Built In function > (load "a.lsp") Additional requirements Want to print each expression that is read in. Want to print the value returned by the expression Definition (defun my-trace-load (filename &aux next-expr next-result) (with-open-file (f filename :direction :input) (do ((next-expr (read f nil) (read f nil))) ((not next-expr)) (format t "~%~%Evaluating '~a'" next-expr) (setf next-result (eval next-expr)) (format t "~% Returned: '~a'" next-result)))) CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 21 CSCI Programming in Lisp; Instructor: Alok Mehta 7

8 Read-Line, Read-Char Read-Line Reads an individual line (terminated by a carriage return) Returns it as a character string > (read-line)hello World Hello World Read-Char Reads an individual character Returns it as a character > (read-char)x #\x ;; This is Lisp notation for the character x CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 22 Symbols We've used symbols as names for things A symbol is much more than just a name Includes: name, package, value, function, plist (Property List) A symbol is a "substantial object" Some functions for manipulating symbols symbol-name, symbol-plist, intern, Details are in Chapter 8 of textbook CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 23 Symbol Names By default Lisp symbol names are upper case > (symbol-name 'abc) "ABC" Can use " " to delimit symbol names > (list ' abc ) ; no conversion "abc" > (list ' Lisp 1.5 ' ' abc ' ABC ) ( Lisp 1.5 abc ABC) ; Note that only ABC doesn't have delimiter (default) Intern creates new symbols > (set (intern ' 5.1/5) ) 999) 999 > 5.1/5) 999 CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 24 CSCI Programming in Lisp; Instructor: Alok Mehta 8

9 Packages Package A name space for symbols Large programs use multiple packages > (defpackage "MY-APPLICATION" ;; Creates new package (:use "COMMON-LISP" "MY-UTILITIES") ;; Other packages (:nicknames "APP") (:export "WIN" "LOSE" "DRAW")) ;; Symbols exported #<The MY-APPLICATION package> > (in-package my-application) ;; Sets this to be default New symbols are (by default) created in default package The default package, when Lisp is started is COMMON-LISP- USER The COMMON-LISP packages is automatically used CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 25 Numbers Number crunching is one of Lisp's strengths Many data types, automatically converted from one to another Many numeric functions Example: Factorial program was easier in Lisp (no overflow!) Four distinct types Types: Integer, Floating Point Number, Ratio, and Complex Number Examples: 100, , 3/2, #c(a b) ; #c(a b) = a+bi Predicates: integerp, floatp, ratiop, complexp Basic rules for automatic conversion If function receives floating point #'s, generally returns floating point #'s If a ratio divides evenly (for example, 4/2), it will be converted to integer If complex # has an imaginary part of zero, converted to a real CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 26 Subset of Type Hierarchy Subset of Type Hierarchy T Number Complex Real Rational Float Lisp Expression Return Value (setf a 12); 12 (type a 'bit); NIL (type a 'fixnum); T (type a 'integer); T (integerp a); T (rationalp a); T (realp a); T (numberp a); T Integer Ratio Fixnum Bignum Long-float Double-float Single-float Short-float Bit CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 27 CSCI Programming in Lisp; Instructor: Alok Mehta 9

10 More on Numbers Conversion (float) (truncate) (floor) (ceiling) (round) > (mapcar #'float '(1 2/3.5)) ( ) Comparison Use = to compare for equality (also, <,<=, >, >=, /=) > (= 4 4.0) T Other Misc. functions Max Min (expt x n) = X^n (exp x) = E^x (log x n) = log n X; N is optional (default = natural log) sqrt, sin, cos, tan CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 28 Eval Eval - Evaluates an expression and returns its value > (eval '( )) 6 Top-level is also called the read-eval-print loop Reads expression, evaluates it, prints value, loops back > (defun our-toplevel () (loop (format t "%~> ") (print (eval (read)))) Eval Inefficient - slower than running compiled code Expression is evaluated without a lexical context CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 29 Macros Macros A common way to write programs that write programs Defmacro is used to define macros Example: A macro to set its argument to NIL > (defmacro nil! (x) (list 'setf x nil)) > (nil! A) ;; Expands to (setf A NIL), is then evaluated NIL macro-expand-1 Generates macro expansion (not eval'ed) > (macroexpand-1 '(nil! A)) (SETF A NIL) T CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 30 CSCI Programming in Lisp; Instructor: Alok Mehta 10

11 Macros Typical procedure call (defun) Evaluate arguments Call procedure Bind arguments to variables inside the procedure Macro procedure (defmacro) Macros do not evaluate their arguments When a macro is evaluated, an intermediate form is produced The intermediate form is evaluated, producing a value CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 31 Example: Manually Define Pop Review of the built in operation Pop : Implements Stack data structure Pop operation > (setf a '( )) > (pop a) 1 > a ( ) How would you emulate this using other functions? Attempt 1: Remove the element 1 from A > (setf a (rest a)) ( ) ;; A is set correctly to ( ), but we want 1 to be returned Attempt 2: Remove first element AND return it > (prog1 (first a) (setf a (rest a))) Attempt 3: Write a Lisp expression that generates above expression > (list 'prog1 (list 'first a) (list 'setf a (list 'rest a))) CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 32 Our-Pop, using Macro Convert Lisp expression into a macro (Our-Pop) > (defmacro our-pop (stack) (list 'prog1 (list 'first stack) (list 'setf stack (list 'rest stack)))) Note similarity to Defun Example Call > (OUR-POP a) Notes The parameter A is NOT evaluated A is substituted for stack wherever the variable stack appears (list 'prog1 (list 'first a) (list 'setf a (list 'rest a))) Intermediate form is generated (prog1 (first a) (setf a (rest a))) Intermediate form is evaluated A is set to (rest A); the first element is returned CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 33 CSCI Programming in Lisp; Instructor: Alok Mehta 11

12 Our-Pop using Defun Why doesn t this (defun) work the same way? > (defun our-pop (stack) (prog1 (first stack) (setf stack (rest stack)))) > (setf a '( )) > (our-pop a) 1 > a ( ) Reason: Lisp passes parameters by-value The value of A is COPIED into the variable stack Any changes to the variable stack are done to the COPY, and NOT the original variable A When the function returns, the original value of A is unchanged CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 34 Significance of Eval Steps Macro evaluation has several steps (as noted) The parameter A is NOT evaluated A is substituted for stack wherever the variable stack appears Intermediate form is generated Intermediate form is evaluated Note that A is evaluated at step 4 above (not step 1) Why does this matter? Answer: For the same reason that it matters in C/C++ macros You may not want arguments evaluated at all Or, you may want them evaluated multiple times Macros give this flexibility CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 35 Backquotes Significance of Evaluation Steps (cont) Consider > (defmacro our-if-macro (conditional then-part else-part) (list 'if conditional then-part else-part)) > (defun our-if-fun (conditional then-part else-part) (if conditional then-part else-part)) > (if (= 1 2) (print "Equal") (print "Not Equal")) Lisp evaluates all parameters of OUR-IF-FUN before function is called Backquote Mechanism Forward quotes: Entire next expression is not evaluated > (defun temp () (setf a '(a b c d e))) Backquote: Next expression is not evaluated (with exceptions) > (defun temp () (setf a `(a b c d e))) > (defun temp (x) (setf a `(a b c d e,x)) The,x expression is evaluated; the value of X is used. CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 36 CSCI Programming in Lisp; Instructor: Alok Mehta 12

13 Backquotes (cont.) Exceptions - Backquote evaluates the following,variable - Evaluates the value of the variable > (setf x '(h i j)) > (setf a `(a b c,x e f)) (A B C (H I J) E F),@variable - Splices the elements of a list > (setf a `(a b c,@x e f)) (A B C H I J E F) Backquotes simplify macro development > (defmacro our-if-macro (conditional then-part else-part) (list 'if conditional then-part else-part)) ;; old way > (defmacro our-if-macro (conditional then-part else-part) `(if,conditional,then-part,else-part)) CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 37 Backquotes simplify macros Original version of our-pop > (defmacro our-pop (stack) (list 'prog1 (list 'first stack) (list 'setf stack (list 'rest stack)))) Our-pop redefined using backquotes > (defmacro our-pop (stack) `(prog1 (first,stack) (setf,stack (rest,stack)))) Syntax is much closer to the intermediate form Macros can be defined with following parameters Optional (&optional) Rest (&rest) Key (&key) CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 38 Macro Design Macro: take a number n, evaluate its body n times Example call > (ntimes 10 (princ ".")). NIL First attempt (incorrect) > (defmacro ntimes (n &rest body) `(do ((x 0 (+ x 1))) ((>= x,n)),@body)) For example call, within body of macro n bound to 10 body bound to ((princ ".")) (do ((x 0 (+ x 1))) ((>= x 10)) (princ ".")) Macro works for example. Why is it incorrect? CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 39 CSCI Programming in Lisp; Instructor: Alok Mehta 13

14 Inadvertent Variable Capture Consider Initialize x to 10, increment it 5 times > (let ((x 10)) (ntimes 5 (setf x (+ x 1))) x) 10 Expected value: 15 Why? Look at expansion > (let ((x 10)) (do ((x 0 (+ x 1))) ((>= x 5)) (setf x (+ x 1))) x) X is used in let and in the iteration setf increments iteration variable! CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 40 Gensym Gives New Symbol Gensym Generates a new (uninterned) symbol > (defmacro ntimes (n &rest body) ; Still incorrect though (let ((g (gensym))) `(do ((,g 0 (+,g 1))) ((>=,g,n)),@body))) The value of symbol G is a newly generated symbol How does this avoid the problem? What if the call has a variable G? Look at the expansion of (let ((x 10)) (ntimes 5 (setf x (+ x 1))) x) CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 41 Expansion of ntimes (2) Substitute for N and BODY > (let ((x 10)) (let ((g (gensym))) `(do ((,g 0 (+,g 1))) ((>=,g,5)),@((setf x (+ x 1))))) x) Generate intermediate form > (let ((x 10)) (do ((#:G34 0 (+ #:G34 1))) ((>= #:G34 5)) (setf x (+ x 1))) x) Evaluate 15 This works for our example but... CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 42 CSCI Programming in Lisp; Instructor: Alok Mehta 14

15 Multiple Evaluation What happens when we want to debug > (let ((x 10) (niteration 3)) (ntimes niteration (setf x (+ x 1))) x) 13 To debug, insert a print expression > (let ((x 10) (niteration 3)) (ntimes (print niteration) (setf x (+ x 1))) x) The argument is evaluated multiple times Apparent when argument causes side-effects What if the argument was a (setf ) Non-intuitive: Expect argument to be evaluated only once. CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 43 Avoiding Multiple Evaluation Solution is to copy value when you get into macro Use copy when needed within macro > (defmacro ntimes (n &rest body) (let ((g (gensym)) (h (gensym))) `(let ((,h,n)) (do ((,g 0 (+,g 1))) ((>=,g,h)),@body)))) This is correct > (let ((x 10) (niteration 3)) (ntimes (print niteration) (setf x (+ x 1))) x) 3 13 CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 44 Expansion of Ntimes (Final) Pprint is a useful function for Pretty PRINTing expressions > (pprint (macroexpand-1 '(ntimes (print niteration) (setf x (+ x 1))))) (LET ((#:G93 (PRINT NITERATION))) (DO ((#:G92 0 (+ #:G92 1))) ((>= #:G92 #:G93)) (SETF X (+ X 1)))) Problems of Multiple Evaluation and Inadvertent Variable Capture Examples of errors that can occur when working with macros Errors are common in Lisp as well as languages like C/C++ CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 45 CSCI Programming in Lisp; Instructor: Alok Mehta 15

16 Multiple Evaluation in Pop Looking back at our Pop macro It suffers from multiple evaluation We can't use same technique, though Need to get the first AND do a setf to change the value > (defmacro our-pop (stack) `(prog1 (first,stack) (setf,stack (rest,stack)))) Textbook solution avoids multiple evaluation Page 301 Uses a function get-setf-expansion to get to inner details of setf CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 46 Case Study: Expert Systems Overview of using Lisp for Symbolic Pattern Matching Rule Based Expert Systems and Forward Chaining Backward Chaining and PROLOG Motivational example Given: A set of Facts A set of Rules Desired result Answer complex questions and queries CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 47 Smart Animal Guessing Facts about an animal named Joey F1. (Joey s mother has feathers) F2. (Joey does not fly) F3. (Joey swims) F4. (Joey is black and white) F5. (Joey lives in Antarctica) Rules about animals in general R1. If (animal X has feathers) THEN (animal X is a bird) R2. If (animal X is a bird) and (animal X swims) and (animal X does not fly) and (animal X is black and white) THEN (animal is a penguin) R3. If (animal X s mother Z) THEN (animal X Z) Example: if (animal X s mother has feathers) then (animal X has feathers) R4. If (animal X Z) THEN (animal s mother Z) Notes By combining the facts and rules, we can deduce that Joey is a penguin, and that the Joey s mother is a penguin. CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 48 CSCI Programming in Lisp; Instructor: Alok Mehta 16

17 Symbolic Pattern Matching Symbolic pattern matching example Match F1 with the IF part of R1 F1. (Joey s mother has feathers) R1. If (animal X has feathers) THEN (animal X is a bird) The expression (Joey s mother has feathers) matches the pattern (animal X has feathers). The association (animal X = Joey s mother) is implied In general Symbolic pattern matching matching an ordinary expression (e.g. fact) to a pattern expression Unification: more advanced version of pattern matching match two pattern expressions to see if they can be made identical Find all substitutions that lead to this CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 49 Rule Based Expert System Rule Based Expert Systems Once the pattern matching step is done, then we know that Rule R1 can be combined with fact F1 F1. (Joey s mother has feathers) R1. If (animal X has feathers) THEN (animal X is a bird) The association (animal X = Joey s mother), along with the second part of the rule (animal X is a bird) leads to a derived fact: (Joey s mother is a bird) CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 50 Forward Chaining Basic philosophy: Given a set of rules R and a set of facts F, what new facts (DF) can be derived? DF1: Joey has feathers (R3,F1) DF2: Joey s mother is a bird (R1, F1) DF3: Joey is a bird (R1,DF1) [or, (R3,DF2)] DF4: Joey s mother does not fly (R4, F2) DF5: Joey s mother swims (R4, F3) DF6: Joey s mother is black and white (R4, F4) DF7: Joey s mother lives in Antarctica (R4, F5) DF8: Joey is a penguin (R2, DF3, F2, F3, F4) DF9: Joey s mother is a penguin (R4, DF8) or (R2, DF2, DF5, DF4, DF6) CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 51 CSCI Programming in Lisp; Instructor: Alok Mehta 17

18 Backward Chaining Basic philosophy Can a statement (e.g. Joey is a penguin) be proven given the current set of facts and rules? Work backwards, to determine what facts, if true, can prove that Joey is a penguin (or prove that Joey is not a penguin). B1. R2: (Joey is a penguin) IF (a) Joey is a bird; (b) Joey swims; (c) Joey does not fly; and (d) Joey is black and white B2. R1: (Joey is a bird) IF (Joey has feathers) B4. R3: (Joey has feathers) IF (Joey s mother has feathers) DF1. (Joey has feathers), since we know (Joey s mother has feathers (F1) DF2. (Joey is a bird), since we know (Joey has feathers) (DF1) DF3. (Joey is a penguin), since (a), (b), (c), and (d) are known to be true (DF2, F3, F2, F4 respectively) The fact (Joey is a penguin) can be derived CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 52 Does this apply in the real world? Given a clinical specimen, need to know what tests to perform? Example facts about a specific patient specimen (to test whether a person has Syphilis): F1. Automated Reagin Test result is Reactive, Titer=8 F2. Microheme Agglutination Test is Non-Reactive F3. Specimen is from a pregnant woman F4. Prior history indicates a result of Reactive, Titer=2 F5. Prior test was performed 12 months ago Example rules R1. IF (Automated Reagin Test is Reactive, Titer >= 4) AND (Microheme Agglutination Test is Non-Reactive) THEN (Rapid Plasma Reagin test must be performed) R2. IF (Specimen is from a pregnant woman) THEN (Microheme Agglutination Test must be performed) R3. IF (Specimen is from a pregnant woman) THEN (Automated Reagin Test must be performed twice) Sample questions: What tests need to be performed? (Forward chaining) Should we do the RPR test? (Backward chaining) Is the specimen considered abnormal? (Backward chaining) CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 53 Lisp Lisp is a good language for implementing expert systems. Concise programs Flexible processing of lists Basic implementations are shown in chapters Other applications of expert systems Mathematics: Calculus, geometry Computer configuration, electronic circuits Evaluate geological formations, planned investments Diagnosis of infections CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 54 CSCI Programming in Lisp; Instructor: Alok Mehta 18

19 Building an Expert System Knowledge representation how to represent facts, patterns, rules how to represent sets of these Build a pattern matcher Build the inference engine Forward Chaining and/or Backward Chaining CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 55 Implementing Pattern Matching Want a procedure to match patterns Input Animal X has feathers (pattern) ((? X) has feathers) ; Uses (? Var) for pattern variable Joey s mother has feathers (regular expression or Fact) ((mother Joey) has feathers) Returns Mapping between pattern variables ( (X (mother Joey)) ) Example call > (match '((? X) has feathers) '((mother Joey) has feathers) ) ((X (mother Joey))) > (match '((? X) has (? Z)) '(Joey has feathers))) ((X Joey) (Z feathers)) CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 56 Return values of Match Return value is a set of variable bindings Example ((X Joey) (Z feathers)) General Form ( (var1 value1) (var2 value2) (varn valuen) ) What if the two patterns don t match? First attempt: On failure, return NIL > (match '((? X) has feathers)) '(Joey does not fly)) NIL But consider... > (match '(Joey has feathers) '(Joey has feathers))) This matches, but there is no need to bind any variables. So, need to return SUCCESS with a list of zero variable bindings: ( ) NIL <-- NIL = ( ) Need to differentiate between failed match and match with no variable bindings CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 57 CSCI Programming in Lisp; Instructor: Alok Mehta 19

20 Return values of Match (cont.) Approach taken by Winston/Horn Note: This is NOT the only way to do it NIL = Success, empty list of pattern variables FAIL = Symbol returned when the pattern and datum don t match Examples > (match '((? X) has feathers) '((mother Joey) has feathers)) ((X (mother Joey))) > (match '((? X) has (? Z)) '(Joey has feathers))) ((X Joey) (Z feathers)) > (match '((? X) has feathers)) '(Joey does not fly)) FAIL > (match '(Joey has feathers) '(Joey has feathers))) NIL ; Treated as an empty list CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 58 Match Function Definition Function definition for MATCH: 4 basic branches ;; Calculates and returns bindings (if successful) ;; Or, returns 'FAIL (defun match (p d &optional bindings) ;; 1. If P and D are both atoms, ;; If they re equal, it s a match, otherwise FAIL ;; e.g. (match 'FEATHERS 'FEATHERS) ;; 2. If P is a pattern variable ;; Assign the value of D to the pattern variable in P ;; e.g. (match '(? X) 'JOEY) ;; should assign the value JOEY to the variable X ;; 3. If P and D are both Lists ;; Recursively solve for matches ;; e.g. (match '(A B (? X) (D E)) '(A B C (D E))) ;; should recursively call match on (A vs. A) ;; (B vs. B) ((? X) vs. C) ((D E) vs. (D E)) ;; 4. Any other case (e.g. atom vs. list, etc.) ;; FAIL ) CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 59 Match: Case 1, Case 4 Part 1: Build up Cond infrastructure Implement case 1 (P and D are both atoms) Implement case 4 (Everything Else) (defun match (p d &optional bindings) (cond ((and (atom p) (atom d)) ;; Case 1: Both p and d are atoms ;; If P and D are equal: Match. Return bindings ;; Otherwise, return FAIL (if (eql p d) bindings 'FAIL)) ( Case 2 ) ( Case 3 ) (t ;; Case 4: Any other case. Return FAIL 'FAIL) ) ) CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 60 CSCI Programming in Lisp; Instructor: Alok Mehta 20

21 Match: Case 3 Case 3 (P and D are lists and need to be solved recursively) Algorithm ;; A) Match the first pair, to get new bindings ;; B) If first pair failed, ;; C) return fail ;; D) Otherwise, using the bindings returned ;; by step (A), match remaining pairs Code (defun match (p d &optional bindings) (cond ( Case 1 ) ( Case 2 ) ((and (listp p) (listp d)) ; P and D are both Lists ;; Recursively solve for matches (let ((result (match (first p) (first d) bindings))) ;(A) (if (eq 'fail result) ;(B) 'FAIL ;(C) (match (rest p) (rest d) result)))) ;(D) ( Case 4 ) )) CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 61 Match, Case 2 Case 2: P is a variable, D is a piece of data Example: P=(? X); D=Joey Make the binding (X Joey) Add it to the bindings already defined Old Bindings: ( (A apple) (B banana) ) After adding: ( (X Joey) (A apple) (B banana) ) Code for adding a new binding to a list of bindings (defun add-binding (p d bindings) (cons (list (second p) d) bindings)) CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 62 Match, Case 2 (continued) Note: Before adding a binding, need to check if the binding already exists If binding exists, it should match previous binding Example 1 > (match '((? X) (? Y) implies (? X) (? Z)) (Joey smokes implies Joey (will get cancer))) ( (X Joey) (Y smokes) (Z (will get cancer))) NOT ((X Joey) (Y smokes) (X Joey) (Z (will get cancer))) When the algorithm finds (X Joey), no new binding should be created Example 2 > (match '((? X) (? Y) implies (? X) (? Z)) (Joey smokes implies Mary (will get cancer))) FAIL This should fail because X cannot be bound to both Joey and Mary When the algorithm finds (X Joey) while trying to bind (X Mary), the routine should return FAIL CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 63 CSCI Programming in Lisp; Instructor: Alok Mehta 21

22 Match, Case 2 (continued) Example 1 (match '(? X) 'Joey '((X Joey) (Y smokes) (Z (will get cancer))) Example 2 (match '(? X) 'Mary '((X Joey) (Y smokes) (Z (will get cancer))) Example 3 (match '(? X) 'Joey '((Y smokes) (Z (will get cancer))) Algorithm ;; 1. Check if variable is already bound ;; 2. If bound, try to match the value of the variable ;; to the datum ;; 3. If bound and the binding matches, return binding ;; (nothing new needs to be done). (Example 1) ;; 4. If bound and the binding doesn t match, return FAIL ;; (Example 2) ;; 5. If not bound, add a binding (Example 3) CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 64 Match, Case 2 (continued) Find-binding: Uses Assoc > (find-binding '(? X) '((X Joey) (Y smokes) (Z (will get ))) (X Joey) Match (defun match (p d &optional bindings) (cond ( Case 1 ) ((and (listp p) (eq (second p) '?)) ; Is p=~ (? X) (let (binding (find-binding p bindings)) ; (1) (if binding ; (2) (match (second binding) d bindings) ; (3,4) (add-binding p d bindings) ; (5) ))) ( Case 3 ) ( Case 4 ) )) CSCI Programming in Lisp; Instructor: Alok Mehta; 4.ppt 65 CSCI Programming in Lisp; Instructor: Alok Mehta 22

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

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

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

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

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

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

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

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

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

More information

CS 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

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

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

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

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

Allegro CL Certification Program

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

More information

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

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

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

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

FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 5. LISP: MAKRA, DATOVÁ STRUKTURA ZÁZNAM

FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 5. LISP: MAKRA, DATOVÁ STRUKTURA ZÁZNAM FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 5. LISP: MAKRA, DATOVÁ STRUKTURA ZÁZNAM 2011 Jan Janoušek MI-FLP Evropský sociální fond Praha & EU: Investujeme do vaší budoucnosti MACROS Introduction to macro system

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

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

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

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

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

An introduction to Scheme

An introduction to Scheme An introduction to Scheme Introduction A powerful programming language is more than just a means for instructing a computer to perform tasks. The language also serves as a framework within which we organize

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

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

Lecture #5 Kenneth W. Flynn RPI CS

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

More information

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

(defmacro while (condition &body body) `(iterate loop () (if,condition (loop)))))

(defmacro while (condition &body body) `(iterate loop () (if,condition (loop))))) ; PARCIL - A Parser for C syntax In Lisp version 0.1a copyright (c) 1992 by Erann Gat, all rights reserved This program is free software; you can redistribute it and/or modify it under the terms of the

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

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

A little bit of Lisp

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

More information

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

An Introduction to Scheme

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

More information

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

Symbolic Computation and Common Lisp

Symbolic Computation and Common Lisp Symbolic Computation and Common Lisp Dr. Neil T. Dantam CSCI-56, Colorado School of Mines Fall 28 Dantam (Mines CSCI-56) Lisp Fall 28 / 92 Why? Symbolic Computing: Much of this course deals with processing

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

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

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

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

(defmacro for ((var start stop) &body body) (do ((,var,start (1+,var)) (limit,stop)) ((>,var

(defmacro for ((var start stop) &body body) (do ((,var,start (1+,var)) (limit,stop)) ((>,var 9 Variable Capture Macros are vulnerable to a problem called variable capture. Variable capture occurs when macroexpansion causes a name clash: when some symbol ends up referring to a variable from another

More information

a little more on macros sort of like functions, but..

a little more on macros sort of like functions, but.. a little more on macros 1 sort of like functions, but.. one of the most interesting but tricky aspects of Lisp. unlike functions, macros don't evaluate their arguments; they compute on unevaluated expressions

More information

Associative Database Managment WIlensky Chapter 22

Associative Database Managment WIlensky Chapter 22 Associative Database Managment WIlensky Chapter 22 DB-1 Associative Database An associative database is a collection of facts retrievable by their contents» Is a poodle a dog? Which people does Alice manage?»

More information

Symbolic Reasoning. Dr. Neil T. Dantam. Spring CSCI-561, Colorado School of Mines. Dantam (Mines CSCI-561) Symbolic Reasoning Spring / 86

Symbolic Reasoning. Dr. Neil T. Dantam. Spring CSCI-561, Colorado School of Mines. Dantam (Mines CSCI-561) Symbolic Reasoning Spring / 86 Symbolic Reasoning Dr. Neil T. Dantam CSCI-561, Colorado School of Mines Spring 2019 Dantam (Mines CSCI-561) Symbolic Reasoning Spring 2019 1 / 86 Introduction Definition: Symbolic Reasoning Inference

More information

Vectors in Scheme. Data Structures in Scheme

Vectors in Scheme. Data Structures in Scheme Data Structures in Scheme Vectors in Scheme In Scheme, lists and S-expressions are basic. Arrays can be simulated using lists, but access to elements deep in the list can be slow (since a list is a linked

More information

Associative Database Managment

Associative Database Managment Associative Database Managment WIlensky Chapter 22 DB-1 Associative Database An associative database is a collection of facts retrievable by their contents» Is a poodle a dog? Which people does Alice manage?»

More information

Essentials of Programming Languages Language

Essentials of Programming Languages Language Essentials of Programming Languages Language Version 5.3 August 6, 2012 The Essentials of Programming Languages language in DrRacket provides a subset of functions and syntactic forms of racket mostly

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

Essentials of Programming Languages Language

Essentials of Programming Languages Language Essentials of Programming Languages Language Version 6.90.0.26 April 20, 2018 The Essentials of Programming Languages language in DrRacket provides a subset of functions and syntactic forms of racket mostly

More information

Structure Programming in Lisp. Shared Structure. Tailp. Shared Structure. Top-Level List Structure

Structure Programming in Lisp. Shared Structure. Tailp. Shared Structure. Top-Level List Structure Structure 66-2210-01 Programming in Lisp Lecture 6 - Structure; ase Study: locks World Lisp's use of pointers Let you put any value anywhere Details are taken care of by the Lisp interpreter What goes

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

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

CSC312 Principles of Programming Languages : Functional Programming Language. Copyright 2006 The McGraw-Hill Companies, Inc.

CSC312 Principles of Programming Languages : Functional Programming Language. Copyright 2006 The McGraw-Hill Companies, Inc. CSC312 Principles of Programming Languages : Functional Programming Language Overview of Functional Languages They emerged in the 1960 s with Lisp Functional programming mirrors mathematical functions:

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

Copyright (c) 1988, by David Michael Betz All Rights Reserved Permission is granted for unrestricted non-commercial use

Copyright (c) 1988, by David Michael Betz All Rights Reserved Permission is granted for unrestricted non-commercial use XLISP: An Object-oriented Lisp Version 2.0 February 6, 1988 by David Michael Betz 127 Taylor Road Peterborough, NH 03458 (603) 924-6936 (home) Copyright (c) 1988, by David Michael Betz All Rights Reserved

More information

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

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

More information

Functional Programming. Pure Functional Languages

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

More information

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

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

CMPUT325 Extensions to Pure Lisp. Extensions to Pure Lisp. Bob Price and Russ Greiner. 5th October 2004

CMPUT325 Extensions to Pure Lisp. Extensions to Pure Lisp. Bob Price and Russ Greiner. 5th October 2004 CMPUT325 Extensions to Pure Lisp Bob Price and Russ Greiner 5th October 2004 Bob Price and Russ Greiner CMPUT325 Extensions to Pure Lisp 1 Extensions to Pure Lisp Extensions to Pure Lisp Side Eects (setq,

More information

1 CLWEB INTRODUCTION 1

1 CLWEB INTRODUCTION 1 1 CLWEB INTRODUCTION 1 1. Introduction. This is CLWEB, a literate programming system for Common Lisp by Alex Plotnick plotnick@cs.brandeis.edu. It is modeled after the CWEB system by Silvio Levy and Donald

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

Robot Programming with Lisp

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

More information

Design Issues. Subroutines and Control Abstraction. Subroutines and Control Abstraction. CSC 4101: Programming Languages 1. Textbook, Chapter 8

Design Issues. Subroutines and Control Abstraction. Subroutines and Control Abstraction. CSC 4101: Programming Languages 1. Textbook, Chapter 8 Subroutines and Control Abstraction Textbook, Chapter 8 1 Subroutines and Control Abstraction Mechanisms for process abstraction Single entry (except FORTRAN, PL/I) Caller is suspended Control returns

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

19 Machine Learning in Lisp

19 Machine Learning in Lisp 19 Machine Learning in Lisp Chapter Objectives Chapter Contents ID3 algorithm and inducing decision trees from lists of examples. A basic Lisp implementation of ID3 Demonstration on a simple credit assessment

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

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

CS 342 Lecture 7 Syntax Abstraction By: Hridesh Rajan

CS 342 Lecture 7 Syntax Abstraction By: Hridesh Rajan CS 342 Lecture 7 Syntax Abstraction By: Hridesh Rajan 1 Reading SICP, page 11-19, Section 1.1.6 Little Schemer, Chapter 2 2 The Idea of Syntax Abstraction Problem. Often programming tasks are repetitive,

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

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

Functions & First Class Function Values

Functions & First Class Function Values Functions & First Class Function Values PLAI 1st ed Chapter 4, PLAI 2ed Chapter 5 The concept of a function is itself very close to substitution, and to our with form. Consider the following morph 1 {

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

A Brief Introduction to Common Lisp

A Brief Introduction to Common Lisp A Brief Introduction to Common Lisp David Gu Schloer Consulting Group david_guru@gty.org.in A Brief History Originally specified in 1958, Lisp is the second-oldest highlevel programming language in widespread

More information

Meet the Macro. a quick introduction to Lisp macros. Patrick Stein / TC Lisp Users Group /

Meet the Macro. a quick introduction to Lisp macros. Patrick Stein / TC Lisp Users Group / Meet the Macro a quick introduction to Lisp macros Patrick Stein / TC Lisp Users Group / 2009-07-14 Attack Plan Some other things called macros First look at Lisp macros More advanced macros Uh-oh, my

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

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

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

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

Tail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d)

Tail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d) CMSC 330: Organization of Programming Languages Tail Calls A tail call is a function call that is the last thing a function does before it returns let add x y = x + y let f z = add z z (* tail call *)

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

UMBC CMSC 331 Final Exam

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

More information

LISP - QUICK GUIDE LISP - OVERVIEW

LISP - QUICK GUIDE LISP - OVERVIEW http://www.tutorialspoint.com/lisp/lisp_quick_guide.htm LISP - QUICK GUIDE Copyright tutorialspoint.com LISP - OVERVIEW John McCarthy invented LISP in 1958, shortly after the development of FORTRAN. It

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

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

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

Object Oriented Programming (OOP)

Object Oriented Programming (OOP) Object Oriented Programming (OOP) o New programming paradigm o Actions Objects o Objects Actions o Object-oriented = Objects + Classes + Inheritance Imperative programming o OOP (Object-Oriented Programming)

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

CS 11 Haskell track: lecture 1

CS 11 Haskell track: lecture 1 CS 11 Haskell track: lecture 1 This week: Introduction/motivation/pep talk Basics of Haskell Prerequisite Knowledge of basic functional programming e.g. Scheme, Ocaml, Erlang CS 1, CS 4 "permission of

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

Functional Languages. Hwansoo Han

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

More information

Extra Lecture #7: Defining Syntax

Extra Lecture #7: Defining Syntax Extra Lecture #7: Defining Syntax In effect, function and class definitions extend the Python language by adding new commands and data types. However, these are highly constrained extensions. For example,

More information

CSE 341 Section Handout #6 Cheat Sheet

CSE 341 Section Handout #6 Cheat Sheet Cheat Sheet Types numbers: integers (3, 802), reals (3.4), rationals (3/4), complex (2+3.4i) symbols: x, y, hello, r2d2 booleans: #t, #f strings: "hello", "how are you?" lists: (list 3 4 5) (list 98.5

More information

Imperative languages

Imperative languages Imperative languages Von Neumann model: store with addressable locations machine code: effect achieved by changing contents of store locations instructions executed in sequence, flow of control altered

More information