Skip to content

Land of Lisp - Ch 5

assocation lists

(defparameter *my-list*
    '(  (key1 (value1a valueb valuec))
        (key2 (value2a valueb valuec))
        (key3 (value3a valueb valuec))
        (key4 (value4a valueb valuec))
        (key5 (value5a valueb valuec))
        (key3 (value3d valuee valuef))))

; format is (assoc key list).. e.g.
> (assoc key3 *my-list*)
; will return..
(key3 (value3a valueb valuec))
; only returns the first matching key

quasi-quoting

Can mark code in data if you use a back-tick and a comma.

> (defparameter *foo* "foo")
> `(data data ,*foo* data ,*foo* data)  ; back-tick and commas

(DATA DATA "foo" DATA "foo" DATA)

append

> (append '(1 2 3) '(4 5 6))
(1 2 3 4 5 6)

> (append '((1 2) (3 4)) '(5 6))
((1 2) (3 4) 5 6)

Higher Order Functions

mapcar

(mapcar #'function list)

applies function to each item of list and generates a new list

apply

takes items in a list and passes them as the parameters to function.

> (apply #'append '( (1 2) (3 4) (5) (6) ) )
; applies the append function to each list in the list to generate...
(1 2 3 4 5 6)
; which is the same as calling...
>(append '(1 2) '(3 4) '(5) '(6))

find

(defun walk (direction)
  (let
    ((next
        (find
             direction
             (cdr (assoc *location* *edges*))    ; lists all edge             *location*
             :key #'cadr )))    ; in (garden west door) cadr [i.e. west] is what we are searching on
    (if next
        (progn
           (setf *location* (car next))
           (look))
        '(you cannot go that way.))))
> (find 'y '((5 x) (3 y) (7 z)) :key #'cadr)
(3 Y)

> (find 'y '(5 . x) (3 . y) 7 . z)

push

adds an item to the front of a list (must be a named list?)

> (defparameter *nums* '(2 3))
> (push '1 *nums*)
(1 2 3)

other list handling functions

(remove-if #'predicate list) - remove all items for which predicate is true (remove-if-not #'predicate list)