lisp base

一 、quote

lisp 使用s-expr表示数据和代码,通常会将第一项作为函数,而将后续元素当做参数传给第一项进行计算。可以通过quote来进行其他解析,quote可用(‘)表示:

1  ( + 1 12   2
3 
4  ‘(+ 1 15   (+ 1 1)

二 、反引号(·) 

(·)按键(~)为同一个键盘按键。作用和quote差不多,但可以使其中部分字符串保留原解析,需要使用,放在需要保留原解析的字符串之前。

 `(+  1 ,(+ 0 1))
  (+  1 1)

三、 #’

该操作符表示对函数的引用

四、控制结构

 do

(do ((x 1 (+ x 1)) 
         (y 1 (* y 2))) 
         ((> x 5) y) 
         (print y) 
         (print 'working))            

cond

(cond 
     ((evenp a) a) ;if a is even return a 
     ((> a 7) (/ a 2)) ;else if a is bigger than 7 return a/2 
     ((< a 5) (- a 1)) ;else if a is smaller than 5 return a-1
     (t 17)) ;else return 17 

2

case

(setq x 'd)
(case x 
      (a 5) 
      ((d e) 7) 
      ((b f) 3) 
      (otherwise 9))
7
    

loop

(setq a 4)
(loop 
     (setq a (+ a 1)) 
     (when (> a 6) (return a)))

7 

if

(if t 6 5) 
6
(if nil 6 5)
5

五、block

Common Lisp 的构造区块(block)的基本操作符:progn 、block 以及 tagbody 。

progn主体中的表达式会顺序求值并返回最后一个表达式的值。

(progn
    (format t "a")
    (format t "b")
    (+ 11 12))
ab
23

block相当于带有特别出口的progn。

(block head
    (format t "Here we go.")
    (return-from head 'idea)
    (format t "We'll never see this."))
Here we go.
IDEA

tagbody大多数迭代操作符都隐含一个tagbody。

(tagbody
    (setf x 0)
    top
      (setf x (+ x 1))
      (format t "~A " x)
      (if (< x 10) (go top)))
1 2 3 4 5 6 7 8 9 10
NIL

return宏把传入的参数当做封闭区块nil的返回值。

(block nil
    (return 27))
27

在一个block(明确定义的或隐含的),不论return-from或者return都不会运行。

六、函数

可通过 symbol-function 给函数配置某个名字:

(setf (symbol-function 'add2)
  #'(lambda (x) (+ x 2)))

新的全局函数可以这样定义,用起来和 defun 所定义的函数一样:

(add2 0)
 2

 

通过 defun 或 symbol-function 搭配 setf 定义的函数是全局函数。你可以像存取全局变量那样,在任何地方存取它们。定义局部函数也是有可能的,局部函数和局部变量一样,只在某些上下文内可以访问。

局部函数可以使用 labels 来定义,它是一种像是给函数使用的 let 。它的第一个实参是一个新局部函数的定义列表,而不是一个变量规格说明的列表。列表中的元素为如下形式:

 

 

posted on 2013-12-06 18:02  d&lufd  阅读(319)  评论(0编辑  收藏  举报

导航