基于sbcl的common-lisp是否有添加(列表)功能?

时间:2016-02-09 21:29:03

标签: common-lisp

嘿伙计们我试图分解一个复杂的问题并且能够在不在列表中创建列表的情况下添加元素将使问题变得更容易。我已经完成了大量的谷歌搜索,并且在common-lisp中找不到添加功能的任何提及。我还要提一下,我正在尝试将其添加到列表的末尾。

- 我已经看到了推送宏,但由于某种原因无法编译。我收到了非法的电话。

- 我尝试过使用cons,但这不会起作用,因为它会在我使用的主列表中生成多个列表。我需要将每个元素放在一个列表中,这样才没有用。

- 使用列表会产生与缺点相同的问题,因为我将再次获得分层列表。

必须有一些方法可以在不创建分层列表的情况下将元素添加到列表中。我是lisp的新手,所以如果这是初级的,我会道歉。

2 个答案:

答案 0 :(得分:2)

我相信你正在寻找追加。

CL-USER> (append '(:a :b :c) '(1 2 3))
(:A :B :C 1 2 3)

http://www.lispworks.com/documentation/HyperSpec/Body/f_append.htm#append

答案 1 :(得分:1)

When working with linked lists (cons cell based lists) it is often helpful to "think backwards". You said you want to add elements to the end of the list, but the optimal way to add something to a linked list is to add it to the front. So if you are able to turn your problem around you might use function getTextWidth(text, fontSize, fontFace) { var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); context.font = fontSize + 'px ' + fontFace; return context.measureText(text).width; } // Then call it like this: console.log(getTextWidth('hello world', 22, 'Arial')); // 105.166015625 console.log(getTextWidth('hello world', 22)); // 100.8154296875 after all.

For instance, if I where to create a function to build a range as a list I could do this:

cons

But this would result in a backwards range:

(defun make-range (from to result)
  (if (<= from to)
    (make-range (1+ from) to (cons from result))
    result))

However, fixing this is as simple as reversing the list when I'm done building it.

* (make-range 1 5 ())
(5 4 3 2 1)

Reversing a list once is in many cases an overhead we can live with, and something you see a lot in functional programming.

相关问题