TUTORIAL 2 CSCI3230 (2014-2015 First Term) By Paco WONG 1.

Slides:



Advertisements
Similar presentations
09 Examples Functional Programming. Tower of Hanoi AB C.
Advertisements

CS 63 LISP Philip Greenspun's Tenth* Rule of Programming:
ANSI Common Lisp 3. Lists 20 June Lists Conses List Functions Trees Sets Stacks Dotted Lists Assoc-lists.
Scheme in Scheme. Why implement Scheme in Scheme  Implementing a language is a good way to learn more about programming languages  Interpreters are.
Functional Programming. Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends.
1 Programming Languages and Paradigms Lisp Programming.
TUTORIAL 3 CSCI3230 ( First Term) By Leo LIU Paco WONG CAO Qin 1 Hands on.
Lisp Recitation (cse471/598 Fall 2007 ) Aravind Kalavagattu.
Functional Programming COMP2003 A course on functional programming using Common Lisp Dr Eleni Mangina
ITERATIVE CONSTRUCTS: DOLIST Dolist is an iterative construct (a loop statement) consisting of a variable declaration and a body The body states what happens.
Introduction to Artificial Intelligence Lisp Ruth Bergman Fall 2002.
First Lecture on Introductory Lisp Yun Peng. Why Lisp? Because it’s the most widely used AI programming language Because AI researchers and theoreticians.
CMSC 471 LISP. Why Lisp? Because it’s the most widely used AI programming language Because it’s good for writing production software (Graham article)
CSE S. Tanimoto Explicit Function Application 1 Explicit Application of Functions, Functional Arguments and Explicit Evaluation Implicit and explicit.
Mapping And Iteration So far, the only Lisp mechanism we have considered, which allows an action to be performed repeatedly is recursion. Most programming.
Functional programming: LISP Originally developed for symbolic computing First interactive, interpreted language Dynamic typing: values have types, variables.
Functional Programming COMP2003 A course on functional programming using Common Lisp Dr Eleni Mangina
LISP A brief overview. Lisp stands for “LISt Process” –Invented by John McCarthy (1958) –Simple data structure (atoms and lists) –Heavy use of recursion.
COMP 205 – Week 11 Dr. Chunbo Chu. Intro Lisp stands for “LISt Process” Invented by John McCarthy (1958) Simple data structure (atoms and lists) Heavy.
LISP 1.5 and beyond A very quick tour. Data Atoms (symbols) including numbers – All types of numbers including Roman! (well, in the early days) – Syntactically.
Lisp: a history Developed by John McCarthy in the 1950’s. Developed by John McCarthy in the 1950’s. Only Fortran has higher “seniority” Only Fortran has.
F UNCTIONAL P ROGRAMMING 05 Functions. F UNCTIONS - G LOBAL F UNCTIONS fboundp Tells whether there is a function with a given symbol as its name > (fboundp.
Yu-Tzu Lin ( 林育慈 )
Functional Programming 02 Lists
The Case primitive: matches the evaluated key form against the unevaluated keys by using eql The general format of case is the following: (case (... ).....
Mitthögskolan 10/8/ Common Lisp LISTS. Mitthögskolan 10/8/2015 2Lists n Lists are one of the fundamental data structures in Lisp. n However, it.
1 Lists in Lisp and Scheme. 2 Lists are Lisp’s fundamental data structures. Lists are Lisp’s fundamental data structures. However, it is not the only.
Basic Lisp CIS 479/579 Bruce R. Maxim UM-Dearborn.
For Monday Read Chapter 3 Homework: –Lisp handout 2.
1 Lisp Functions –Built-in functions –Defining functions –Function Evaluation and Special Forms defun, if Control statements –Conditional if, cond –Repetition.
Lecture 2-1CS250: Intro to AI/Lisp Intelligent Agents Lecture 3-2 October 14 th, 1999 CS250.
KU NLP Artificial Intelligence1 Ch 15. An Introduction to LISP q 15.0 Introduction q 15.1 LISP: A Brief Overview  Symbolic Expressions, the Syntactic.
TUTORIAL 1 CSCI3230 ( First Term) By Tony YI 1.
Common lisp A functional programming language. Useful URL:
The Loop Macro Many of the CL “functions” are actually macros (let, progn, if, etc) The most complicated macro in CL is probably the Loop macro –The Loop.
Lecture 6-2CS250: Intro to AI/Lisp Programming in Your Favorite Language Lecture 5-2 February 11 th, 1999 CS250.
Lisp Functional Language or Applicative Language –Achieves its effect by applying functions, either recursively or through composition Powerful, expressive,
LISP Data Types Functional Programming Academic Year Alessandro Cimatti
Building user-defined functions: the progressive envelopment technique The idea: define combinations of LISP primitives through a sequence of experiments.
Introduction to LISP. Lisp Extensible: It lets you define new operators yourself Lisp programs are expressed as lisp data structures –You can write programs.
UMBC CMSC Common Lisp II. UMBC CMSC Input and Output Print is the most primitive output function > (print (list 'foo 'bar)) (FOO BAR) The.
PRACTICAL COMMON LISP Peter Seibel 1.
Control in LISP More on Predicates & Conditionals.
Milos Hauskrecht (PDF) Hieu D. Vu (PPT) LISP PROGARMMING LANGUAGE.
1 Variable Declarations Global and special variables – (defvar …) – (defparameter …) – (defconstant …) – (setq var2 (list 4 5)) – (setf …) Local variables.
Comparative Programming Languages Functional programming with Lisp/Scheme.
1 Outline Review Introduction to LISP Symbols and Numbers Lists Writing LISP Functions LISPWorks.
Section 15.4, 15.6 plus other materials
Defining Macros in Lisp
Example of formula (defun roots (a b c) (list
Modern Programming Languages Lecture 20 Fakhar Lodhi
Getting Started with Lisp
LISP A brief overview.
PZ10CX - LISP Programming Language Design and Implementation (4th Edition) by T. Pratt and M. Zelkowitz Prentice Hall, 2001 Section Appendix A.6.
First Lecture on Introductory Lisp
J.E. Spragg Mitthögskolan 1997
FP Foundations, Scheme In Text: Chapter 14.
Modern Programming Languages Lecture 20 Fakhar Lodhi
CSE S. Tanimoto Explicit Function Application
Lisp: Using Functions as Data
LISP A brief overview.
John McCarthy Pioneer in AI Also Lisp Formalize common-sense reasoning
Defining Macros in Lisp
Abstraction and Repetition
Lisp: Using Functions as Data
Common Lisp II.
The general format of case is the following: (case <key form>
LISP primitives on sequences
Lists in Lisp and Scheme
Procedures with optional parameters which do not require matching arguments Example: consider the exponent function which may take one argument, m, in.
Presentation transcript:

TUTORIAL 2 CSCI3230 ( First Term) By Paco WONG 1

Outline Predicates Conditional constructs Iteration Function Macro Structure Property list 2

Type Predicates FunctionMeaning TYPEP object data_typeIs the type of object data_type? SUBTYPEP subtype data_typeIs the subtype a subtype of data_type? FunctionMeaning (Is the argument data_type?) NULL argumentIs the argument ()? ATOM argumentIs the argument an atom (not a cons)? SYMBOLP argumentIs the argument a symbol? CONSP argumentIs the argument a cons? LISTP argumentIs the argument a list? General Specific Example 1 > (symbolp 10) NIL > (atom 10) T > (typep 10 'atom) T ;same as the last result

Equality Predicates FunctionMeaning = x yNumbers only and ignore type EQ x yAre the two objects implementationally identical? Same memory location (e.g. identical symbols) EQL x yAre the two objects conceptually identical? EQ x y OR Number of same type with the same value OR Character objects of the same character EQUAL x yAre the two objects isomorphic? Same printed representations or expression Example 2 > (setq q1 '(abc 123)) (ABC 123) > (setq q2 '(abc 123)) (ABC 123) > (eq q1 q2) NIL ;cont’ > (eql q1 q2) NIL > (eql (car q1) (car q2)) T > (equal q1 q2) T

Conditional Constructs AND {form}* If either one of the forms is NIL, returns NIL; Otherwise, returns the value of the last form. NOT argument If the argument is NIL, returns T; Otherwise, returns NIL. OR {form}* Evaluating the forms in order, if one of the forms is non- NIL, immediately returns that value; Otherwise, returns NIL.

Conditional Constructs IF test then [else] Evaluates a test form If the result is non-NIL, next form is then. If the result is NIL, next form is the optional else. Example 3 > (setq p 10) 10 > (setq d 3) 3 > (if (eql (mod p d) 0) (list '* p d) (list '+ (list '* d (floor (/ p d))) (mod p d))) (+ (* 3 3) 1) To enclose multiple forms in a form, use (PROGN {form}*)

Conditional Constructs COND { (test {form}*) }* Evaluates the test form in order If the value of test form is non-NIL the next set of forms is evaluated and returns its result. If none of the test forms non-NIL, returns NIL. Example 4.1 > (setq person 'Sam) SAM > (cond ((eql person 'Peter) 'Boss) ((eql person 'Sam) 'Staff1001) ((eql person 'Paco) 'Staff1002) (t 'Intruder!));Otherwise STAFF1001 Example 4.2 > (setq person 'John) JOHN > (cond ((eql person 'Peter) 'Boss) ((eql person 'Sam) 'Staff1001) ((eql person 'Paco) 'Staff1002) (t 'Intruder!);must be eval (t 'Alarm));ignore INTRUDER!

Indefinite Iteration LOOP {forms}* Repeatedly evaluates a series of forms Example 5 >(setq x 3) >(loop (print x) (setq x (- x 1)) (if (zerop x) (return "Go!"))) "Go!"

Specific Iteration: DO DO ({ (variable [initial-value [step-form]]) }*) (end-test {result}*) {declaration}* {tag | statement}*) Repeatedly evaluates a series of forms until the end-test returns non-NIL.

Specific Iteration: DO Example 6 >(setq x 3) >(do ((a x (- a 1))) ((zerop a) "Go!") (print a)) "Go!" (DO ((a x (- a 1))) ((zerop a)"Go!") (printa)) initial-valuevariablestep-form end-testresult statement

Specific Iteration: DO* DO* ({ (variable [initial-value [step-form]]) }*) (end-test {result}*) {declaration}* {tag | statement}*) Looks exactly the same except that the name DO is replaced by DO* Except that the bindings and steppings of the variables are performed sequentially rather than in parallel Try the following expression. (dolist (x '(c u h k) x) (print x)) Pay attention to the last line of the output.

Let LET ({var | (var value)}*) {declaration}* {form}* Execute a series of forms {form}* with specified variables {var | (var value)}* Example 7 > (let ((x 3));don’t forget the () (loop (print x) (setq x (- x 1)) (if (zerop x) (return "Go!")))) "Go!"

YOUR CONTROL CONSTRUCTS Much more powerful than #define macros in C

Named Function DEFUN name lambda-list {declaration|doc-string}* {form}* The name is a global name lambda-list specifies names for the parameters of the function Example 8 > (defun decompose(p d) (if (eql (mod p d) 0) (list '* p d) (list '+ (list '* d (floor (/ p d))) (mod p d)))) DECOMPOSE > (decompose 10 4);the decompose function can be called globally (+ (* 4 2) 2)

Lambda Expression LAMBDA lambda-list. body Defines an unnamed function Useful when you are going to use a function only once 15 Example 9 > ((lambda (p d) (if (eql (mod p d) 0) (list '* p d) (list '+ (list '* d (floor (/ p d))) (mod p d)))) 10 4) (+ (* 4 2) 2) Example 8 > (defun decompose (p d) (if (eql (mod p d) 0) (list '* p d) (list '+ (list '* d (floor (/ p d))) (mod p d)))) DECOMPOSE > (decompose 10 4) (+ (* 4 2) 2)

Block and Exits BLOCK name {form}* Provide a structured lexical non-local exit facility. Example: Exit a loop until it hits a return (see Example 5) Example 10 >(block blk-A (block blk-B (return-from blk-A 10) 20)) ;cascaded 10 ;not 20 >(block nil (return 27)) ;the name is nil, same as (return-from nil (return 27)) 27

Block and Exits The body of a defun form implicitly enclosed in a block. The block has the same name as the function. Example 11 >(defun find-food (trapp) (format t "see the cheese. ") (if trapp (return-from find-food (format t "there is a trap. turn away."))) (format t "eat it greedily.")) >(FIND-FOOD t) see the cheese. there is a trap. turn away. NIL

Macro DEFMACRO name lambda-list [[ {declaration}* | doc- string ]] {form}* Its parameters are not evaluated before passing to the marco. They are evaluated in place of the macro call. Example 12 > (defmacro macro_power (f) `(let ((x 1) (y 2)),f)); Back quote ` and comma, MACRO_POWER > (macro_power (+ y 2)) 4 > (macro_power (+ x y)) 3 > (macroexpand-1 '(macro_power (+ y x)));Expansion of the above (LET ((X 1) (Y 2)) (+ Y X));Substitution takes place T

YOUR DATA TYPE

Structure DEFSTRUCT {structure-name | (slot-name {options}*)} [doc-string] {slot-description}+ Defines a new data type whose instances have named slots Arranges for setf to work properly on such access functions Functions associated with structure of name sname Access function for each slot slotname: sname-slotname Predicate: sname-p Constructor function: make-sname Copier function: copy-sname Other options :conc-name, :constructor, :copier, :predicate, :include, :print-function, :type, :named, :initial-offset

Structure Example 13 > (defstruct classroom (chair 30) (whiteboard 2) (computer 1)) CLASSROOM;new structure > (setq shb504 (make-classroom));constructor #S(CLASSROOM :CHAIR 30 :WHITEBOARD 2 :COMPUTER 1) > (setq erb1009 (make-classroom :chair 50));assign new value to slot #S(CLASSROOM :CHAIR 50 :WHITEBOARD 2 :COMPUTER 1) > (classroom-computer erb1009);access function 1 > (setf (classroom-whiteboard erb1009) 3);assign new value with setf 3 > erb1009;see the result #S(CLASSROOM :CHAIR 50 :WHITEBOARD 3 :COMPUTER 1)

Property List A kind of tabular structure Entries are associated with an indicator An object with unique identity (destructive operations) GET symbol indicator &optional default Searches the property list of symbol for an indicator eq to indicator. If one is found, then the corresponding value is returned; otherwise default is returned. Example 14 > (setf (get 'Tony 'Mobile) 'XIAOMI) XIAOMI > (get 'Tony 'Mobile) XIAOMI > (setf (get 'Tony 'CallNo) ' ) > (symbol-plist 'Tony);Show the whole property list (CALLNO MOBILE XIAOMI)

Summary S-expression Atom and list Evaluation and its control Form, QUOTE and EVAL Binding variable explicitly SET, SETQ and SETF Cons cell and list CONS, CAR, CDR, NTHCDR, NTH, APPEND, … Lispbox Predicates TYPEP, SUBTYPEP, EQL, … Conditional constructs IF THEN ELSE, COND, … Iteration LOOP, DO, … Let Function DEFUN Macro DEFMACRO Structure DEFSTRUCT Property list GET Feedback: or

Try it yourself 1. Write a recursive function Fibonacci(n) that returns the n th number in the Fibonacci sequence. One reclusive version and iterative version. 2. Given a list of length n, we want to remove the cons cells from j to j+1, where j is from 0 to n Write a merge sort function for a list of number. 4. Use mapcar with unnamed and named function. Hands on [W6 W9 H7]

Hints Exercise 2 > (setq l '( )) ( ) > (nthcdr 3 l) ( ) > (nthcdr 3 l) ( ) > (setf (cdr (nthcdr 3 l)) (nthcdr 6 l)) ;because clisp doesn't allow setf on nthcdr ( ) > l ( ) Exercise 3 Exercise 1

Suggested Readings Common Lisp the Language, 2nd Edition OnLisp Common LISP Hints tutorial.html tutorial.html 26

Reference Common Lisp the Language, 2nd Edition Common LISP Hints tutorial.html tutorial.html George F. Luger. Artificial Intelligence 5 th ed. Addison Wesley. Wendy L. Milner. Common LISP, a Tutorial. Prentice Hall. 27

Appendix: Lambda-list A lambda-list has five parts, any or all of which may be empty: Specifiers for the required parameters. These are all the parameter specifiers up to the first lambda-list keyword; if there is no such lambda- list keyword, then all the specifiers are for required parameters. Specifiers for optional parameters. If the lambda-list keyword &optional is present, the optional parameter specifiers are those following the lambda-list keyword &optional up to the next lambda-list keyword or the end of the list. A specifier for a rest parameter. The lambda-list keyword &rest, if present, must be followed by a single rest parameter specifier, which in turn must be followed by another lambda-list keyword or the end of the lambda-list. Specifiers for keyword parameters. If the lambda-list keyword &key is present, all specifiers up to the next lambda-list keyword or the end of the list are keyword parameter specifiers. The keyword parameter specifiers may optionally be followed by the lambda-list keyword &allow-other-keys. Specifiers for aux variables. These are not really parameters. If the lambda-list keyword &key is present, all specifiers after it are auxiliary variable specifiers. " " Reference: