Procedures with optional parameters which do not require matching arguments Example: consider the exponent function which may take one argument, m, in.

Slides:



Advertisements
Similar presentations
Lisp Control and Data Structures CIS 479/579 Bruce R. Maxim UM-Dearborn.
Advertisements

5/11/2015IT 3271 Types in ML (Ch 11) datatype bool = true | false; datatype 'element list = nil | :: of 'element * 'element list n Predefined, but not.
Lisp – Introduction יעל נצר מערכות נבונות סמסטר ב' תשס"ו.
Procedures with optional parameters which do not require matching arguments Example: consider the exponent function which may take one argument, m, in.
ITERATIVE CONSTRUCTS: DOLIST Dolist is an iterative construct (a loop statement) consisting of a variable declaration and a body The body states what happens.
Functional Programming COMP2003 A course on functional programming using Common Lisp Dr Eleni Mangina
SICP Symbolic data Symbol: a primitive type Generalization Symbolic differentiation.
LISP primitives on sequences FIRST (or CAR) and REST (or CDR) take lists apart. Consider the list (First day of the semester). * (first '(First day of.
Introductory Lisp Programming Lecture # 2 Main Topics –Basic Lisp data types –Lisp primitives –Details of list handling Cons cells (boxes) & their representation.
Programming in Lisp; Instructor: Alok Mehta Programming in Lisp Recursion, Data Abstraction, Mapping, Iteration.
Symbolic Expressions (S Expressions) Syntax: Opening and Closing parenthesis having elements in between. List represented in LISP: (A B2 C3 Shahid) (A.
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.
TUTORIAL 2 CSCI3230 ( First Term) By Paco WONG 1.
Alok Mehta - Programming in Lisp - Data Abstraction and Mapping Programming in Lisp Data Abstraction and Mapping.
The Case primitive: matches the evaluated key form against the unevaluated keys by using eql The general format of case is the following: (case (... ).....
PRACTICAL COMMON LISP Peter Seibel 1.
PRACTICAL COMMON LISP Peter Seibel 1.
For Monday Read Chapter 3 Homework: –Lisp handout 2.
Multiple Returns and Extra Parameters “LISP is unique in its capability to return more than one value (or no value at all) from a form. This neatly avoids.
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.
CSE 341, S. Tanimoto Lisp Defining Functions with DEFUN Functions are the primary abstraction mechanism available in Lisp. (Others are structures.
Arrays Part 9 dbg. Arrays An array is a fixed number of contiguous memory locations, all containing data of the same type, identified by one variable.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: Types and Classes Dr. Hyunyoung Lee.
Lecture 6-2CS250: Intro to AI/Lisp Programming in Your Favorite Language Lecture 5-2 February 11 th, 1999 CS250.
Building user-defined functions: the progressive envelopment technique The idea: define combinations of LISP primitives through a sequence of experiments.
UMBC CMSC Common Lisp II. UMBC CMSC Input and Output Print is the most primitive output function > (print (list 'foo 'bar)) (FOO BAR) The.
Procedures with optional parameters which do not require matching arguments Example: consider the exponent function which may take one argument, m, in.
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.
Structures “The programmer, like the poet, works only slightly removed from pure thought-stuff. He builds his castles in the air, from air, creating by.
Introduction to LISP Atoms, Lists Math. LISP n LISt Processing n Function model –Program = function definition –Give arguments –Returns values n Mathematical.
1 Outline Review Introduction to LISP Symbols and Numbers Lists Writing LISP Functions LISPWorks.
Arrays Chapter 7.
Basic Scheme February 8, 2007 Compound expressions Rules of evaluation
Defining Macros in Lisp
Array, Strings and Vectors
Data Structures in Lisp
6.001: Structure and Interpretation of Computer Programs
Array Array is a variable which holds multiple values (elements) of similar data types. All the values are having their own index with an array. Index.
Using Lisp Lisp is a interactive system
Prof: Dr. Shu-Ching Chen TA: Yimin Yang
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
First Lecture on Introductory Lisp
Imperative Data Structures
Modern Programming Languages Lecture 21 Fakhar Lodhi
Data abstraction, revisited
Prof: Dr. Shu-Ching Chen TA: Haiman Tian
Closure Closure binds a first-class function and a lexical environment together This is a complex topic, so we will build up our understanding of it we.
Object Oriented Programming in java
Data Structures (CS212D) Week # 2: Arrays.
CSE S. Tanimoto Explicit Function Application
Types and Classes in Haskell
Lecture #9 מבוא מורחב.
Lecture 12: Message passing The Environment Model
John McCarthy Pioneer in AI Also Lisp Formalize common-sense reasoning
Defining Macros in Lisp
Defining Functions with DEFUN
Peter Seibel Practical Common Lisp Peter Seibel
Abstraction and Repetition
Data Structures in Lisp
Data Structures in Lisp
Common Lisp II.
Programming Languages
Defining Macros in Scheme
The general format of case is the following: (case <key form>
List manipulation Consider student database, where each student is represented by the following list: * (setf student1 '((Paul Bennett) ((hw1 4.3) (hw2.
LISP primitives on sequences
Presentation transcript:

Procedures with optional parameters which do not require matching arguments Example: consider the exponent function which may take one argument, m, in which case it returns the square of m, or two arguments, m and n, in which case it returns n power of m. * (defun exponent (m &optional n) ; here n is an optional parameter. (if n ; if the value for an optional parameter is (if (zerop n) ; not provided, it is assumed NIL. 1 (* m (exponent m (- n 1)))) (* m m))) EXPONENT * (exponent 2) 4 * (exponent 2 3) 8

Optional parameters may be given default values, if we do not want their default value to be NIL. Example: the exponent procedure * (defun exponent (m &optional (n 2)) (if (zerop n) 1 (* m (exponent m (- n 1))))) EXPONENT * (exponent 2) 4 * (exponent 2 3) 8

Optional parameters eliminate the need for auxiliary procedures, because the first call uses the default value, while all other recursive calls ignore it * (trace exponent) (EXPONENT) * (exponent 4) | 1 Entering: EXPONENT, argument-list: (4) | 2 Entering: EXPONENT, argument-list: (4 1) | | 3 Entering: EXPONENT, argument-list: (4 0) | | 3 Exiting: EXPONENT, value 1 | 2 Exiting: EXPONENT, value 4 | 1 Exiting: EXPONENT, value 16 16

Example Consider math-quiz, a function which posts n math problems to the user (who can set n as she wants) tutoring her in arithmetic (+, -, * or / is to be set by the user, as well as the range of numbers to be exercised). (defun math-quiz (&optional (op '+) (range 100) (n 3)) (dotimes (i n) (exercise (random range) op (random range)))) (defun exercise (num1 op num2) (format t "~%The expression is ") (format t "~a ~a ~a" num1 op num2) (format t "~% ... and the answer is ...") (print (eval (list op num1 num2)))) * (math-quiz) ;all parameters are optional, no argument is required. The expression is 85 + 97 ... and the answer is ... 182 The expression is 25 + 76 101 The expression is 47 + 60 107

Example (cont.) Optional parameters are position-dependent. To provide a non-default value for n, we must specify values for all optional parameters that come before n (even if they are their default values). * (math-quiz '+ 100 5) ; ”+” and “100” are the default values for the first two arguments The expression is 61 + 46 ; they must be provided if we want to change the default value ... and the answer is ... ; of the last argument. 107 The expression is 3 + 69 ... and the answer is ... 72 The expression is 34 + 76 110 The expression is 61 + 49 The expression is 3 + 78 81

Keyword parameters. Keyword parameters are similar to optional parameters, except that they are position-independent because bindings are determined by keywords not by order. Example: the math-quiz function. (defun math-quiz2 (&key (op '+) (range 100) (n 3)) (dotimes (i n) (exercise (random range) op (random range)))) (defun exercise (num1 op num2) (format t "~%The expression is ") (format t "~a ~a ~a" num1 op num2) (format t "~% ... and the answer is ...") (print (eval (list op num1 num2)))) * (math-quiz2 :n 2) The expression is 44 + 40 ... and the answer is ... 84 The expression is 84 + 43 127

The rest parameter. This takes as its value the list of all arguments that have been unaccounted for. Example: consider function sum-two which takes only two arguments and adds them. (defun sum-two (number &rest numbers) (sum-two-aux number numbers)) (defun sum-two-aux (sum list-of-numbers) (if (endp list-of-numbers) sum (sum-two-aux (+ sum (first list-of-numbers)) (rest list-of-numbers)))) * (trace sum-two sum-two-aux) (SUM-TWO-AUX SUM-TWO) * (sum-two 2 4 6 3 7) | 1 Entering: SUM-TWO, argument-list: (2 4 6 3 7) | 2 Entering: SUM-TWO-AUX, argument-list: (2 (4 6 3 7)) | | 3 Entering: SUM-TWO-AUX, argument-list: (6 (6 3 7)) | | 4 Entering: SUM-TWO-AUX, argument-list: (12 (3 7)) | | | 5 Entering: SUM-TWO-AUX, argument-list: (15 (7)) | | | 6 Entering: SUM-TWO-AUX, argument-list: (22 NIL) | | | 6 Exiting: SUM-TWO-AUX, value 22 | | | 5 Exiting: SUM-TWO-AUX, value 22 ..... 22

The aux parameter This is not matched to any argument, because it is intended to define auxiliary local variables similar to let*. Example: the both-ends procedure. * (setf whole-list '(a b c d)) ; the value of whole-list must be provided before (A B C D) ; function definition, otherwise an error will occur * (defun both-ends-new (whole-list &aux (first-el (first whole-list)) (last-list (last whole-list))) (cons first-el last-list)) * (trace both-ends-new) (BOTH-ENDS-NEW) * (both-ends-new whole-list) | 1 Entering: BOTH-ENDS-NEW, argument-list: ((A B C D)) | 1 Exiting: BOTH-ENDS-NEW, value (A D) (A D) Various parameters can be combined in the following order: optional parameters come first after regular parameters, next are sole rest parameters followed by key parameters, followed by aux parameters.

Representing structures in Lisp We can create user-defined data types to represent any data type in Lisp. These are called structure types, and they come with automatically created access procedures. defstruct is the primitive that creates new structure types. (defstruct <structure name> (<field name 1> <default value 1>) (<field name 2> <default value 2>) . . . (<field name n> <default value n>)) Example: (defstruct person (sex nil) (personality 'nice))

Lisp structures (cont.) Structures are implemented as vectors, where the type (structure name) is the zero element, field 1 is the first element, … field n is the n-th element. This means that structures are more efficient than lists, because each element can be accessed in a single step. Notes: 1. ) defstruct defines a new data type. 2.) defstruct does not create instances of that data type, but automatically creates a data-constructor procedure, data-reader procedures (a separate one for each field), data type predicate, as well as generalizes the setf primitive to handle the new data type. Example: (setf person-instance-1 (make-person)) ; make-person with no parameters creates a ;new instance of type person with fields filled with default values in defstruct (setf person-instance-2 (make-person :sex 'female)) ; default value changes by ;providing a new value for keyword :sex.

Lisp structures (cont.) To read data from created instances: * (person-sex person-instance-2) FEMALE * (person-personality person-instance-1) NICE Because data is accessed by an automatically generated reader procedure, it is said to be procedurally indexed. To change the values of existing fields: * (setf (person-sex person-instance-1) 'female) * (person-sex person-instance-1)

Lisp structures (cont.) defstruct also creates a data type predicate: * (person-p person-instance-1) T * (person-p '(a b c)) NIL Example: Define a data type rock that contains fields for color, size and worth. Assume that the default color is gray, default size – pebble, default worth – nothing. (defstruct rock (color 'gray) (size 'pebble) (worth 'nothing)) (setf high-hopes-rock (make-rock :color 'gold :worth 'high))

Lisp structures (cont.) A big advantage of structure types is that one structure can include fields of another structure, thus forming a representational hierarchy. Example: Consider structure employee employee salesperson hacker … * (defstruct employee (length-of-service 0) (payment 'salary)) EMPLOYEE * (defstruct (hacker (:include employee)) (preferred-language 'lisp)) HACKER * (setf employee-example (make-employee)) #S(EMPLOYEE :LENGTH-OF-SERVICE 0 :PAYMENT SALARY) * (setf hacker-example (make-hacker)) #S(HACKER :LENGTH-OF-SERVICE 0 :PAYMENT SALARY :PREFERRED-LANGUAGE LISP) * (employee-length-of-service employee-example) * (employee-length-of-service hacker-example)

To print the contents of an instance of a structure: One structure can include another with one or more of the fields repeated in both. In such case, the default value in more specialized structure shadows the default value in more general structure. * (setf employee-example (make-employee)) #S(EMPLOYEE :LENGTH-OF-SERVICE 0 :PAYMENT SALARY) * (defstruct (salesperson (:include employee (payment 'commission))) (preferred-car 'mercedes)) SALESPERSON * (setf salesperson-example (make-salesperson)) #S(SALESPERSON :LENGTH-OF-SERVICE 0 :PAYMENT COMMISSION :PREFERRED-CAR MERCEDES) * (employee-payment hacker-example) SALARY * (employee-payment salesperson-example) COMMISSION To print the contents of an instance of a structure: * (describe hacker-example) #S(HACKER :LENGTH-OF-SERVICE 0 :PAYMENT SALARY :PREFERRED-LANGUAGE LISP) is a named structure of type HACKER. It has as an included structure EMPLOYEE. Its slot names and values are: LENGTH-OF-SERVICE - 0 PAYMENT - SALARY PREFERRED-LANGUAGE - LISP

included in the structure’s definition. Example: To print the structure itself, however, a special printing procedure must be defined and included in the structure’s definition. Example: * (defstruct (employee2 (:print-function print-employee2)) (name 'anna) (ss# 'unknown) (length-of-service 5) (payment 'salary)) EMPLOYEE2 * (defun print-employee2 (structure &rest ignore) (format t "structure for ~a with ss# ~a" (employee2-name structure) (employee2-ss# structure))) PRINT-EMPLOYEE2 * (setf employee-anna (make-employee2)) structure for ANNA with ss# UNKNOWN * (describe employee-anna) structure for ANNA with ss# UNKNOWN is a named structure of type EMPLOYEE2. Its slot names and values are: NAME - ANNA SS# - UNKNOWN LENGTH-OF-SERVICE - 5 PAYMENT - SALARY

Representing tables as association lists: the ASSOC and RASSOC primitives. Consider a two-column table, where the first column contains properties of a given object, and the second column contains the values of these properties. Such object descriptions can be represented by expressions called association lists (or a-lists). These have two different formats: Format 1: ((key-1 value-1) (key-2 value-2) .... (key-n value-n)) Format 2: ((key-1 . value-1) (key-2 . value-2) .... (key-n . value-n)) The assoc primitive searches a-lists by key. Its format is the following: (assoc <key> <a-list>) The rassoc primitive searches a-lists by value, but it works only on a-lists of dotted pairs. Its format is the following: (rassoc <value> <a-list>)

Example: a table of days of the week and their average temperatures. * (setf week-7-1 '((Mon 28) (Tue 32) (Wed 37) (Th 31) (Fri 33) (Sat 26) (Sun 29))) ((MON 28) (TUE 32) (WED 37) (TH 31) (FRI 33) (SAT 26) (SUN 29)) * (assoc 'fri week-7-1) (FRI 33) * (second (assoc 'fri week-7-1)) 33 * (rassoc 26 week-7-1) NIL * (setf week-7-2 '((Mon . 28) (Tue . 32) (Wed . 37) (Th . 31) (Fri . 33) (Sat . 26) (Sun . 29))) ((MON . 28) (TUE . 32) (WED . 37) (TH . 31) (FRI . 33) (SAT . 26) (SUN . 29)) * (assoc 'fri week-7-2) (FRI . 33) * (rest (assoc 'fri week-7-2)) 33 * (rassoc 26 week-7-2) (SAT . 26) * (first (rassoc 26 week-7-2)) SAT

Another example on a-list of dotted pairs: * (setf state-table '((al . alabama) (az . arizona))) ((AL . ALABAMA) (AZ . ARIZONA)) * (assoc 'al state-table) (AL . ALABAMA) * (rest (assoc 'al state-table)) ALABAMA * (assoc 'ct state-table) NIL * (rassoc 'alabama state-table) * (first (rassoc 'alabama state-table)) AL

Representing tables as property lists: the GET primitive. There are two types of values that can be assigned to symbols: Ordinary values. Example: (setf number 5) Property values. These are placed together in a list, called property list (or p-list) and are “attached” to the symbol (i.e. can be accessed only through the symbol itself). Example: consider symbol day-1 with the following properties: avg-temp, sun-rise, and sun-set: * (setf (get 'day-1 'avg-temp) 37) ;setf and get are used in combination 37 ; to get to and set a value for a property * (setf (get 'day-1 'sun-rise) '6h45m) ; of day-1 6H45M * (setf (get 'day-1 'sun-set) '17h10m) 17H10M * (get 'day-1 'sun-rise) ; after a value has been assigned to 6H45M ; a property, get retrieves that value

The DESCRIBE and REMPROP primitives The describe primitive can be used to see the contents of the p-list: * (describe 'day-1) DAY-1 is an internal symbol in package USER. Its value is unbound. Its function definition is unbound. Its property list contains: Property: SUN-SET, Value: 17H10M Property: SUN-RISE, Value: 6H45M Property: AVG-TEMP, Value: 37 The remprop primitive removes a property from the p-list: * (remprop 'day-1 'avg-temp) T

Representing tables as arrays Arrays are represented in the same way as in JAVA, and their indexes start with 0.To declare an array, a combination of SETF and MAKE-ARRAY primitives is used as follows: * (setf array-1 (make-array 10)) ; the first array element is in position 0, the last in position 9 #(0 0 0 0 0 0 0 0 0 0) * (setf array-2 (make-array '(5 2))) ; the first array element is in position 0, 0 #2A((0 0) (0 0) (0 0) (0 0) (0 0)) * (setf array-3 (make-array '(2 5 3))) #3A(((0 0 0) (0 0 0) (0 0 0) (0 0 0) (0 0 0)) ((0 0 0) (0 0 0) (0 0 0) (0 0 0) (0 0 0))) To initialize an array at the same time: * (setf array-1 (make-array 10 :initial-contents '(1 2 3 4 5 6 7 8 9 10))) #(1 2 3 4 5 6 7 8 9 10) * (setf array-2 (make-array '(5 2) :initial-contents '((1 2) (3 4) (5 6) (7 8) (9 10)))) #2A((1 2) (3 4) (5 6) (7 8) (9 10)) The size of array dimension can be determined by the ARRAY-DIMENSION primitive: * (array-dimension array-2 0) 5

Retrieving and changing array elements To retrieve an item from an array, we use the AREF primitive as follows: * array-1 #(1 2 3 4 5 6 7 8 9 10) * (aref array-1 5) ; retrieves the 6-th item 6 * array-2 #2A((1 2) (3 4) (5 6) (7 8) (9 10)) * (aref array-2 2 1) ; retrieves the item in the 3-rd raw, 2-nd column To change the value stored in a specified position, we use a combination of SETF and AREF primitives: * (setf (aref array-1 5) 33) 33 #(1 2 3 4 5 33 7 8 9 10) * (setf (aref array-2 2 1) 66) 66 #2A((1 2) (3 4) (5 66) (7 8) (9 10))

Hash tables: yet another way to represent tables Primitives on hash tables: * (setf table (make-hash-table)) ; initializes the table #<HASH-TABLE 0/37 9B:19F6> * (setf (gethash 'al table) 'alabama) ; modifies the table ALABAMA * (gethash 'al table) ; retrieves values T * (gethash 'ct table) NIL * (remhash 'al table) ; removes a key-value pair from the table * (gethash 'al table) * (clrhash table) ; removes all key-value pairs from the table