宏1

; 宏,句法抽象。其他得通过定义类来实现扩展
; ----------------------------------
(if condition then-form [else-form])
;condition被求值如果非nil执行then-form返回其结果,否则执行else-form返回其结果
;如果condition nil 并且没有else-form返回nil
(if (> 2 4) "oko" "nope")
; ----------------------------------
; 串接子句progn
(if (spam-p current-message)
  (file-in-spam-folder current-message)
  (update-spam-database current-message))
; if只能执行一个子句;所以应该是这样的:
(if (spam-p current-message)
  (progn
    (file-in-spam-folder current-message)
    (update-spam-database current-message)))
; 另外的实现--WHEN,可以执行一系列的子句
(when (spam-p current-message)
  (file-in-spam-folder current-message)
  (update-spam-database current-message))
; when的后台实现
(defmacro when (condition &rest body)
  `(if ,condition (progn ,@body)))
;和when相反的宏 UNLESS除非
;;; 多重分支 cond,依次求值,直到遇到真值,然后求值form*返回
(cond 
  (test-1 form*)
  ......   
  (test-n form*))
; 习惯上最后一个是t.
(cond
  (a (do-x))
  (b (do-y))
  (t (do-z)))
; and or not 逻辑
; and or 是宏 not是函数
; and 遇到nil立即返回nil,否则返回最后一个表达式的值
; or遇到第一个非nil的立即返回其值
; 循环都是宏,用原生goto创建的宏
; DO DOLIST DOTIMES
(dolist (var list-form)
  body-form*)
; list-form求值一次,产生一个列表。然后var在列表上迭代
(dotimes (var count-form)
  body-form*)
; count-form*必须求值为一个整数,var在0----count-1上迭代
; 可以用return退出循环
; do循环
(do (variable-definition*)
  (end-test-form result-form*)
  statement*)
; variable-definition* 格式为(var init-form step-form)
; 没有step-form则var每次迭代都不变 init-form没有则绑定到nil
; 每次迭代开始和所有循环变量被赋初值后,求值end-test-from求值为nil则继续
; 步长在分配变量之前求值
(do ((n 0 (1+ n))
     (cur 0 next)
     (next 1 (+ cur next)))
  ((= 10 n) cur))
; do基本模板三队括号
; Loop宏
; 最简单和最复杂
(Loop
  body-form*)
(do ((nmus nil) (i 1 (1+ i)))
  ((> i 10) (nreverse nums))
  (push i nums))
; 返回1---10
(loop for i from 1 to 10 collecting i )-->(1 2 3 4 5 6 7 8 9 10)
(loop for i fomr 1 to 10 summing (expt x 2)) -->385
(loop for x across "the quikc brown fox" counting (find "aeiou"))
(loop for i below 10
      and a = 0 then b
      and b = 1 then (+ b a)
      finally (return a))



posted @ 2012-04-11 08:43  舜耕山翁  阅读(172)  评论(0编辑  收藏  举报