2013年4月26日星期五

笔记:Practial Common Lisp

命名列表

CL-USER> (getf (list :a 1 :b 2 :c 3) :a)
1



format循环打印

(defun dump-db ()
  (format t "~{~{~a:~10t~a~%~}~%~}" *db*))

其中 ~{ ~} 进入一层循环,~% 换行,~a 打印字符, ~10t 格式化字符串间距


根据指定的selector-fn条件,选取出对应的行,进行更新

(defun update (selector-fn &key title artist rating (ripped nil ripped-p))
  (setf *db*
        (mapcar
         #'(lambda (row)
             (when (funcall selector-fn row)
               (if title    (setf (getf row :title) title))
               (if artist   (setf (getf row :artist) artist))
               (if rating   (setf (getf row :rating) rating))
               (if ripped-p (setf (getf row :ripped) ripped)))
             row) *db*)))


前面加'(),括号里的内容当数据处理,不执行
> (list 1 2 '(+ 1 2))
(1 2 (+ 1 2))

前面加反引号的话,只有,()里面的内容才被解释执行(注意前面有个逗号),其余都当成列表数据
`(1 2 (+ 1 2))       → (1 2 (+ 1 2))
`(1 2 ,(+ 1 2))      → (1 2 3)

加,@() 往里拆一层出来
`(and ,(list 1 2 3))  → (AND (1 2 3))
`(and ,@(list 1 2 3)) → (AND 1 2 3)

闭包

(let ((count 0))
  (list
   #'(lambda () (incf count))
   #'(lambda () (decf count))
   #'(lambda () count)))


赋值
Simple variable:    (setf x 10)
Array:              (setf (aref a 0) 10)
Hash table:         (setf (gethash 'key hash) 10)
Slot named 'field': (setf (field o) 10)


宏参数
  •  &optional 可选
  •  &key  参数以关键字表示(类似perl里的hash)
  •  &rest 剩余参数,也可写作 &body
在宏里面新建变量的时候,记得用上GENSYM,不然命名重复的话,宏展开后执行可能出错



没有评论:

发表评论