Dana Vrajitoru
C311 Programming Languages

Lambda Expressions, Map

Lambda Expressions in Lisp

(lambda (arg-variables...) 
  [documentation-string] 
  [interactive-declaration] 
  body-forms...) 
A lambda expression evaluates to itself.
(lambda (x y) (* x y))
((lambda (x y) (* x y)) 2 3)
6

Map

Examples

Lambda Copy
Making a one-level deep copy of a list:

(defun my-copy (L)
  (mapcar (lambda (x) x) L))

(setq L '(1 2 3 4))   ;=>   (1 2 3 4)
(setq M (my-copy L))  ;=>   (1 2 3 4)
(eq L M)     ;=>  nil
(equal L M)  ;=>  t

Examples Storing a function in a variable:

(setq f (lambda (x) (* x x)))
(lambda (x) (* x x))
(mapcar f '(1 2 3))  ;=>  (1 4 9)
(fset 'g f)  ;=>  (lambda(x) (* x x))
(g 3) ;=> 9

fset
Defines the symbol-function of a symbol and assigns it a particular value.

(fset 'first (symbol-function 'car)) 
;=> #<subr car>
(first '(1 2 3))   ;=>  1 
(fset 'xfirst 'car);=>  car 
(xfirst '(1 2 3))  ;=> 1 
(symbol-function 'xfirst) ;=> car 
(symbol-function (symbol-function 'xfirst))
;=> #<subr car>

Function Indirection
In a function call Lisp will follow a sequence of symbols until it finds a function.

(defun g (x) (* x x)) ; g
(fset 'g1 'g) ; g
(fset 'h 'g1) ; g1
(fset 'g2 (symbol-function 'g))
; (lambda (x) (* x x))
(defun g (x) (+ x 60)) ; g
(g 5)  ; 65
(g1 5) ; 65
(h 5)  ; 65
(g2 5) ; 25

Function eval
Evaluates an expression and returns its value. It performs one more level of indirection than the Ctrl-j.

(setq a "hello") ; "hello"
(setq b 'a)      ; a
b                ; a
(eval b)         ; "hello"
(setq c 'b)      ; b
(eval c)         ; a
(eval a)         ; "hello"
(eval 'a)        ; "hello"
(eval 'b)        ; a