Cons in scheme explanation

此生再无相见时 提交于 2019-12-11 03:56:56

问题


(cons 1 2) gives us (1 . 2).

(cons 3 4) gives us (3 . 4).

So why does (cons (cons 1 2) (cons 3 4)) give us ((1 . 2) 3 . 4)? Why isn't it ((1 . 2) (3 . 4))?


回答1:


Well, it wouldn't be ((1 . 2) (3 . 4)) because that would be a list containing two elements, each a cons pair. I'm guessing what you meant was: why isn't it ((1 . 2) . (3 . 4))?

Well, actually the following two expressions are equivalent:

'((1 . 2) . (3 . 4))
'((1 . 2) 3 . 4)

This has to do with how Scheme's dotted notation works in tandem with its representation of proper lists. Remember that this:

'(1 . (2 . (3 . (4 . ()))))

...would simply be printed as this:

(1 2 3 4)

However, this:

'(1 . (2 . (3 . 4)))

...would be printed like this:

(1 2 3 . 4)

Note that Scheme tries to use the simplified list notation as long as it can—it only falls back to explicitly dotting things once it reaches a pair which doesn't have a pair or the empty list as its cdr element.

Therefore, in your original example, the second element of that cons pair is a pair, so Scheme uses the list notation. That lets it drop the second set of parentheses and the extra dot, yielding the result you encountered.



来源:https://stackoverflow.com/questions/28401857/cons-in-scheme-explanation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!