函数

 1 ;; Common lisp
2
3 ;; define function
4
5 ;; function as the value
6
7 ;; function as the parameter
8 (apply #'+ '(1 2))
9 (apply (symbol-function '+) '(1 2))
10 (apply #'(lambda (x y) (+ x y)) '(1 2))
11
12 (funcall #'+ 1 2 3 4 5)
13
14 (mapcar #'(lambda (x) (* x x)) '(1 2 3 4 5 6 7))
15
16 (sort '(1 2 3 4 5 6 7 8 9 10) #'>)
17
18 ;; function as attribute
19 ;; normal
20 (defun behave (animal)
21 (case animal
22 (dog (wag-tail)
23 (bark))
24 (rat (scurry)
25 (squeak))))
26 (defun wag-tail ()
27 (print "wag tail."))
28 (defun bark ()
29 (print "Wang wang wang."))
30 (defun scurry ()
31 (print "Scurry ->->->->"))
32 (defun squeak ()
33 (print "Zhi zhi zhi."))
34
35 ;; as attribute
36 (defun new-behave (animal)
37 (funcall (get animal 'behavior)))
38 (setf (get 'dog 'behavior)
39 #'(lambda ()
40 (wag-tail)
41 (bark)))
42 (setf (get 'rat 'behavior)
43 #'(lambda ()
44 (scurry)
45 (squeak)))
46
47 ;; Lexical closure
48 (let ((counter 0))
49 (defun new-id () (incf counter))
50 (defun reset-id () (setq counter 0)))
51
52 (defun make-adder (n)
53 #'(lambda (x) (+ x n)))
54
55 (defvar *fun-make-adder-7* (make-adder 7))
56
57 (print (funcall *fun-make-adder-7* 3))
posted @ 2012-03-13 12:37  maxima  阅读(183)  评论(0编辑  收藏  举报