86/ &optional之后的參數(shù)都是選擇性的浅役,缺省為nil:
有的參數(shù)可以被忽略,并可以缺省設(shè)成特定的值问潭。這樣的參數(shù)稱為選擇性參數(shù)(optional parameters)等舔。(相比之下,普通的參數(shù)有時稱為必要參數(shù)「required parameters」) 如果符號&optional出現(xiàn)在一個函數(shù)的形參列表時期虾。
1 > (defun philosoph (thing &optional property);;;缺省
? (list thing 'is property))
PHILOSOPH
1 > (philosoph 'death)
(DEATH IS NIL)
1 > (defun philosoph (thing &optional (property 'fun));;;參數(shù)fun
? (list thing 'is property))
PHILOSOPH
1 > (philosoph 'death)
(DEATH IS FUN)
87/ &key放在一個形參列表原朝,那在&key之后的形參都是選擇性的。
此外镶苞,當(dāng)函數(shù)被調(diào)用時喳坠,這些參數(shù)會被識別出來,參數(shù)的位置在哪不重要茂蚓,而是用符號標(biāo)簽(譯注::)識別出來:
1 > (defun keylist (a &key x y z);;;函數(shù)名及形參
??? (list a x y z));;按序排列
KEYLIST
1 > (keylist 1 :y 2);;;a為1壕鹉,:之后為選擇值,即y值為2
(1 NIL 2 NIL);;按函數(shù)定義好的序列排列數(shù)值聋涨,無值得默認為nil
1 > (keylist 1 :y 3 :x 2);;;a為1御板,:之后為選擇值,即y值為3牛郑,x值為2
(1 2 3 NIL)
1 > (keylist 1 :Z 9 :y 3 :x 2 );;;a為1怠肋,:之后為選擇值,即y值為3淹朋,x值為2笙各,z為9
(1 2 3 9)
88/ single?,當(dāng)實參是只有一個元素的列表時础芍,返回真杈抢。自定義函數(shù)
1 > (defun single? (lst)
? (and (consp lst) (null (cdr lst))))
SINGLE?
1 > (single? '(a))
T
1 > (single? '(a b))
NIL
89/ append1和cons很像,但在列表后面新增一個元素仑性,而不是在前面:
1 > (defun append1 (lst obj)
? (append lst (list obj)))
APPEND1
1 > (append1 '(a b c) 'd);;在列表后面新增一個元素惶楼,末位實參不為列表
(A B C D)
1 > (cons 'd '(a b c) );;在列表前面新增一個元素,末位實參必須為列表
(D A B C)
其他
1 > (append1 '(a b c) '(d 7));;末位若為列表诊杆,則整體作為一個實參并入新列表
(A B C (D 7))
1 > (cons '(a b c) 'd );末位若為一個元素歼捐,則與前列表構(gòu)成一個數(shù)組
((A B C) . D)
90/ map-int,接受一個函數(shù)與整數(shù)n晨汹,并返回將函數(shù)應(yīng)用至整數(shù)0到n-1的結(jié)果的列表豹储。
1 > (defun map-int (fn n)
? (let ((acc nil))
??? (dotimes (i n)
????? (push (funcall fn i) acc))
??? (nreverse acc)))
MAP-INT
1 > (map-int #'identity 10);;接受一個函數(shù)與一個整數(shù),結(jié)果返回整數(shù)以下從0到n-1的列表
(0 1 2 3 4 5 6 7 8 9)
1 > (map-int #'identity 6)
(0 1 2 3 4 5)
1 > (map-int #'(lambda (x) (random 100))
?????????? 10)
(51 45 90 49 72 40 26 38 72 23);;產(chǎn)生10個隨機數(shù)
91/ RANDOM產(chǎn)生隨機數(shù)淘这,從0~n-1中
1 > (random 100)
77;;;隨機數(shù)
1 > (random 100)
72;;隨機數(shù)
1 > (random 100)
17;;隨機數(shù)
92/ filter接受一個函數(shù)與一個列表剥扣,將函數(shù)應(yīng)用至列表元素上時,返回所有非nil元素
4 > (defun filter (fn lst)
? (let ((acc nil))
??? (dolist (x lst)
????? (let ((val (funcall fn x)))
??????? (if val (push val acc))))
??? (nreverse acc)))
FILTER
4 > (filter #'(lambda (x)
????????????? (and (evenp x) (+ x 10)));;;函數(shù)铝穷,作用是偶數(shù)钠怯,+10,并存儲
????????? '(1 2 3 4 5 6 7));;;從此列表中選出偶數(shù)
(12 14 16)
93/ most曙聂,根據(jù)某個評分函數(shù)(scoring function)晦炊,返回列表中最高分的元素。它返回兩個值,獲勝的元素以及它的分數(shù):
4 > (defun most (fn lst)
? (if (null lst)
????? (values nil nil)
????? (let* ((wins (car lst))
???????????? (max (funcall fn wins)))
??????? (dolist (obj (cdr lst))
????????? (let ((score (funcall fn obj)))
??????????? (when (> score max)
????????????? (setf wins obj
??????????????????? max? score))))
??????? (values wins max))))
MOST
4 > (most #'length '((a b) (a b c r y 6 7) (a)));;返回最長的列表和其元素個數(shù)
(A B C R Y 6 7)
7