乐正

Actions speak louder than words.

Sicp-ex2-17

问题

请定义出过程last-pair,它返回只包含给定(非空)表里的最后一个元素的表:

1
2
3
(last-pair (list 23 72 149 34))

(34)

解答

练习2.17 (ex2-17.scm) download
1
2
3
4
5
6
;; Happy hacking Yuez - Emacs ♥ you!

(define (last-pair items)
  (if (= (length items) 1)
      items
      (last-pair (cdr items))))

测试

1
2
3
4
5
6
7
8
9
10
11
(define items (list 1 2 3 4))
;Value: items

(last-pair items)
;Value 16: (4)

(define items (list 1 3 4 (cons 1 3)))
;Value: items

(last-pair items)
;Value 17: ((1 . 3))

draft

« sicp-ex2-18 sicp-ex2-19 »

Comments