方案中要列出的缺点元素与方案中要列出的缺点列表 [英] Cons element to list vs cons list to element in Scheme

查看:123
本文介绍了方案中要列出的缺点元素与方案中要列出的缺点列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在方案中使用cons将元素组合到列表和使用cons将列表组合到元素有什么区别?

What's the difference between using cons to combine an element to a list and using cons to combine a list to an element in scheme?

此外,缺点到底是如何工作的?是否将元素添加到列表的末尾或开头?

Furthermore, how exactly does cons work? Does it add element to the end of the list or the beginning?

谢谢!

推荐答案

原始cons只是将两件事粘在一起,其中有些事被视为列表是偶然的.例如,这可以工作并创建一个 pair (也称为 cons单元格):

The primitive cons simply sticks together two things, the fact that some of those things are considered lists is incidental. For instance, this works and creates a pair (also known as a cons cell):

(cons 1 2)
=> '(1 . 2)     ; a pair

现在,如果cons的第二个参数碰巧是一个列表,则结果将是一个新列表,并且cons的第一个参数将添加到旧列表的开头.换句话说:要创建一个列表,即使它是空的,也需要一个列表:

Now, if the second argument to cons happens to be a list, then the result will be a new list, and the first argument to cons will be added at the head of the old list. In other words: to create a list you need a list, even if it's empty:

(cons 1 '(2 3))
=> '(1 2 3)     ; a list

(cons 1 (cons 2 '()))
=> '(1 2)       ; a list

(cons 1 '())
=> '(1)         ; a list

但是,如果cons的第二个参数不是 列表,那么结果将是一对,或者是不正确的列表,这意味着它不会t以'()结尾,因为它应被视为列表:

But if the second argument to cons is not a list, then the result will be just a pair, or an improper list, meaning that it doesn't end in '() as it should to be considered a list:

(cons '(1 2) 3)
=> '((1 2) . 3) ; a pair, not a list

(cons 1 (cons 2 3))
=> '(1 2 . 3)   ; an improper list

请澄清一下,您不能使用cons在列表末尾添加元素.建立列表的通常方法是从右到左,在头部位置反向添加元素-假设您要建立列表'(1 2 3),则必须按3 2 1的顺序cons >:

Just to clarify, you can't use cons to add elements at the end of a list. The usual way to build a list is going from right-to-left, adding elements in reverse at the head position - say you want to build the list '(1 2 3), then you have to cons the elements in the order 3 2 1:

(cons 3 '())                   ; list is '(3)
(cons 2 (cons 3 '()))          ; list is '(2 3)
(cons 1 (cons 2 (cons 3 '()))) ; list is '(1 2 3)

在极少数情况下,您需要在末尾添加一个元素(相信我,通常这样做意味着您认为算法有误),您可以使用append,它会收到两个列表作为参数:

For those rare occasions where you need to add one element at the end (and believe me, doing so generally means that you're thinking the algorithm wrong) you can use append, which receives two lists as arguments:

(append '(1 2 3) '(4))
=> '(1 2 3 4)

这篇关于方案中要列出的缺点元素与方案中要列出的缺点列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆