简体   繁体   English

获取值未列出 lisp 中的缺点

[英]Getting values not list for cons in lisp

I'm making a function in scheme(lisp) in which I need to cons a list with it reverse, as below:我正在 scheme(lisp) 中创建一个函数,其中我需要将列表与它相反,如下所示:

(cons list (cdr (reverse list)))

consider I have this list '(0 1 2), the desired output would be:考虑我有这个列表'(0 1 2),所需的输出是:

(0 1 2 1 0)

but I get:但我得到:

((0 1 2) 1 0)

is there any function that returns the values of the list, not the list itself?是否有任何函数返回列表的值,而不是列表本身?

You should read up on cons : http://en.wikipedia.org/wiki/Cons你应该阅读conshttp : //en.wikipedia.org/wiki/Cons

cons will pair an element with another. cons将一个元素与另一个元素配对。 If you pair an element with a list, you are adding this element at the beginning of the list.如果您将一个元素与一个列表配对,您就是在列表的开头添加了这个元素。 In your case, the element you are pairing to your reversed list is itself a list.在您的情况下,您与反向列表配对的元素本身就是一个列表。 See the examples on the wiki page.请参阅维基页面上的示例。

What you want here is append , since you want to concatenate those two lists together.您在这里想要的是append ,因为您想将这两个列表连接在一起。

Append it like this:像这样附加它:

(define (mirror ls)
    (if (null? (cdr ls))
        ls
        (let ((x (car ls)))
            (append 
                (list x)
                (mirror (cdr ls))
                (list x)))))

Hope it helps :)希望能帮助到你 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM