开发者

Are pair and list different in Scheme?

I wonder whether '(1 开发者_Go百科. 2) and '(1 2) mean the same data (equal to each other) in Scheme or not? I think they are the same thing, is this correct?


No, they are not the same.

'(1 . 2) means (cons 1 2)

whereas

'(1 2) means (cons 1 (cons 2 nil))


(1 . 2) is sometimes called an improper list, because it is not NIL terminated. (1 2) represented in dot form may be written (1 2 . NIL), but you should not write something like this.


dr rackect explains it much more clearer:

"A pair joins two arbitrary values.....The cons procedure constructs pairs"

(cons 1 2)
'(1 . 2)

(pair? (cons 1 2))
#t

on the other hand

"A list is a combination of pairs that creates a linked list. More precisely, a list is either the empty list null, or it is a pair whose first element is a list element and whose second element is a list."

 (cons 0 (cons 1 (cons 2 null)))
'(0 1 2)

http://docs.racket-lang.org/guide/pairs.html

please LISP has been around since the 50's for accurate answers look at their documentation and example they area around for more than 60 years some people was not even born there.


Yes!

Pairs: (cons y z) creates a pair between the values y and z. Likewise, the (more complicated) expression (cons x (cons y z)) creates a pair between x and the pair (y . z). You can also represent these pairs as '(y . z) and '(x . (y . z))

Lists: A list is just a special type of pair. It's the case where a value is paired onto an already-existing list. Since the very first list has to start somewhere, we always have the null list '() (sometimes called the 'empty list') ready to be paired. So (cons y '()) pairs y with the null list to become the one-item list '(y). Likewise, (cons x '(y)) and (cons x (cons y '())) pair x to the list '(y) to become the list '(x y).

listspairs


List must end with empty list (also termed as null). Below sample code on repl illustrates the difference.

> (cons 1 (cons 2  '())) ; I am a pair as well as list
'(1 2)
(pair?  (cons 1 (cons 2  '()))) 
#t
> (list?  (cons 1 (cons 2  '())))
#t


> (cons 1 (cons 2 3)) ;I am a pair but but not list
'(1 2 . 3)
> (pair? (cons 1 (cons 2 3)))
#t
> (list? (cons 1 (cons 2 3)))
#f   
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜