View on GitHub

Yoy-wiw

A website on lisp.

Download this project as a .zip file Download this project as a tar.gz file

咱也学学Lisp(6)–又见列表

10 Oct 2012

原文见:http://lisp.plasticki.com/

据说蜘蛛吃起来像鸡肉,Lisp用起来像什么,像英语!直接看吧:

CL-USER> (first '(12 24 35))

12

CL-USER> (second '(12 24 35))

24

CL-USER> (rest '(12 24 35))

(24 35)

CL-USER> (nth 3 '(12 24 35))

NIL

CL-USER> (nth 3 '(12 24 35 87))

87

CL-USER> (last '(12 24 35 87))

(87)

函数 (first ) 用于取列表的第一个元素,(second ) 取第二个,(third ) 取第三个 ...

任意一个怎么取,用 (nth X ),注意从 0 开始数。

不要第一个取剩下的,用 (rest ) 函数,取最后一个用 (last ) 函数,注意这两个函数返回列表。

CL-USER> (length '(12 24 35 87))

4

计算列表元素个数用 (length ) 函数。

CL-USER> (cons 12 '(23))

(12 23)

CL-USER> (cons 45 '())

(45)

将一个元素添加进列表用 (cons E ) 函数,称为构造列表。

CL-USER> (append '(12) '(34))

(12 34)

CL-USER> (append '(12 56) '(34 78))

(12 56 34 78)

CL-USER> (append '(12 56) '(34) '(78 99))

(12 56 34 78 99)

函数 (append ) 可以将若干个列表和为一个列表。注意 append 后面需跟列表。

练习一下:

CL-USER> (defun insert (e l)

(append l (cons e '()) l))

INSERT

CL-USER> (insert 34 '(56 98))

?