Lisp EN -- Laboratory 7 -- 2006-2007 --

From Wikiversity
Jump to navigation Jump to search
Important! These pages are somehow outdated and it is recommended to consult the newer version at Functional programming -- 2008-2009 -- (by Ciprian Crăciun).

Lisp EN -- 2006-2007 --

Property lists[edit]

The get function is used to access (and with the use of setf to modify) the property list of a symbol. In CLisp each symbol has an associated property list.

This list can be compared with a key-value mapping that exists for each symbol. The set of property lists can also be compared with the contents of a relational database table in which the symbol is the primary key, the property is a column, and the value is the tuple's value for the given column.

(get <symbol> <property>) => <value>
(setf (get <symbol> <property>) <value>)

In the following example we try to build a parent-child database.

(defmacro father (p c)
    `(setf (get ,c 'father) ,p))

(defmacro mother (p c)
    `(setf (get ,c 'mother) ,p))

(defmacro father? (c)
    `(get ,c 'father))

(defmacro mother? (c)
    `(get ,c 'mother))

(father 'a 'c)
(mother 'b 'c)
(father 'c 'e)
(mother 'd 'e)
(father 'f 'd)
(mother 'g 'd) 

(father? 'c) ;=> a
(mother? 'c) ;=> b
(mother? (father? 'e)) ;=> b

Advanced usage of lambda[edit]

When we call lambda it creates a lexical closure, and holds a reference to all the symbols that were available in the context (and at the time) it was called.

(defun make* (n)
    (lambda (x) (* x n)))

(setf *2 (make* 2))
(setf *3 (make* 3))

(mapcar *2 '(1 2 3 4)) ;=> (2 4 6 8)
(mapcar *3 '(1 2 3 4)) ;=> (3 6 9 12)
(mapcar (make* 5) '(1 2 3 4)) ;=> (5 10 15 20)

Ciprian Dorin Craciun