Lecture 5 - Computer Science at CCSU

Download Report

Transcript Lecture 5 - Computer Science at CCSU

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

optional parameter.

is an

(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 ... and the answer is ...

101 The expression is 47 + 60 ... and the answer is ...

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 ... and the answer is ...

110 The expression is 61 + 49 ... and the answer is ...

110 The expression is 3 + 78 ... and the answer is ...

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 ... and the answer is ...

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

( )) 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) FEMALE

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) 0 * (employee-length-of-service hacker-example) 0

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

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

rassoc

primitive searches a-lists by value, but it works only on a-lists of dotted pairs. Its format is the following: (rassoc )

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)) * (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-1) (FRI 33) * (second (assoc 'fri week-7-1)) 33 * (rassoc 26 week-7-1) NIL * (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) (AL . ALABAMA) * (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 * (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

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 #(0 0 0 0 0 0 0 0 0 0) ; position 9 * (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 6 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 * array-1 #(1 2 3 4 5 33 7 8 9 10) * (setf (aref array-2 2 1) 66) 66 * array-2 #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 # * (setf (gethash 'al table) 'alabama) ; modifies the table ALABAMA * (gethash 'al table) ; retrieves values ALABAMA T * (gethash 'ct table) NIL NIL * (remhash 'al table) ; removes a key-value pair from the table T * (gethash 'al table) NIL NIL * (clrhash table) ; removes all key-value pairs from the table #