List
car cdr cons 用来操作序对
然而如果用序对写成
> (cons 1 (cons 2 (cons 3 4)))
(1 2 3 . 4)就是一个简单的树
car 用来访问左孩子
cdr 用来访问右孩子
例:
> (define tem1 (cons (cons 1 2) (cons 3 4)))
> (car (car tem1))
1
> (car (cdr tem1))
3
> (cdr (car tem1))
2‘
进一步说明 :
‘ car 操作 ‘ 就是获取第一个元素
‘ cdr操作’ 就是获取除了第一个元素的其他所有元素使用这种cons嵌套来的序对系列叫做表
scheme 为了方便构造可以用list基本操作
> (list 1 2 3 4)
(1 2 3 4)
> (cons 1 (cons 2 (cons 3 4)))
(1 2 3 . 4)null?操作用于判断表是不是空表
> (define list1 (list 1 2 3))
> (if (null? list1)
0
1)
1length 用于返回表中的数据有多少
> (length list1)
3然而
length实现可以用递归
> (define (length tem)
(define (len a count)
(if (null? a)
count
(len (cdr a) (+ 1 count))))
(len tem 0))
> (length list1)
3两个表的合并
递归版:
> (add-list (list 1 2 3) (list 4 5 6))
(1 2 3 4 5 6)迭代版:
> (define (add-list l1 l2)
(if (null? l1)
l2
(add-list (cdr l1) (cons (car l1) l2))))
> (add-list (list 1 2 3) (list 4 5 6))
(3 2 1 4 5 6)练习
定义过程last-pair ,返回只包含给定非空表的最后一个元素
> (define (last-pair tem)
(cond ((null? tem) (display "null"))
((= 1 (length tem)) (car tem))
(else (last-pair (cdr tem)))))
> (last-pair (list 1 2 3 4 5))
5
> (last-pair (list 2 3 4 9 0))
0定义过程reverse 返回表中的参数表的反向表
> (define (reverse list-tem)
(define (tem old new)
(if (null? old)
new
(tem (cdr old) (cons (car old) new))))
(tem list-tem (list)))
> (reverse (list 1 2 3 4))
(4 3 2 1)本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!