what is the 'cons' to add an item to the e

2020-02-04 02:52发布

what's the typical way to add an item to the end of the list?

I have a list (1 2 3) and want to add 4 to it (where 4 is the result of an evaluation (+ 2 2))

(setf nlist '(1 2 3))  
(append nlist (+ 2 2))  

This says that append expects a list, not a number. How would I accomplish this?

9条回答
虎瘦雄心在
2楼-- · 2020-02-04 03:15

If the "cons at the front, finish by reversing" idiom isn't suitable for you (if you. for example, need to pass the list on to other functions DURING its construction), there's also the "keep track of the end" trick. However, it's probably cleaner to just build the list by consing to the front of it, then finish by using reverse or nreverse before finally using it.

In essence, this allows you to have the list in the right order while building it, at the expense of needing to keep track of it.

(defun track-tail (count)
  (let* ((list (cons 0 nil))
     (tail list))
    (loop for n from 1 below count
       do (progn
        (setf (cdr tail) (cons n nil))
        (setf tail (cdr tail))
        (format t "With n == ~d, the list is ~a~%" n list)))
    list))

This gives the following output:

CL-USER> (track-tail 5)
With n == 1, the list is (0 1)
With n == 2, the list is (0 1 2)
With n == 3, the list is (0 1 2 3)
With n == 4, the list is (0 1 2 3 4)
(0 1 2 3 4)
查看更多
我只想做你的唯一
3楼-- · 2020-02-04 03:15

You can also use nconc to create the list, which is like append, only it modifies the structure of the input lists.

(nconc nlist (list (+ 2 2)))
查看更多
相关推荐>>
4楼-- · 2020-02-04 03:19

This function might be useful in some situations, it transparently appends a single element to a list, i.e. it modifies the list but returns the appended element (enclosed in a list):

(defun attach1 (lst x)
  (setf (cdr (last lst)) (cons x nil)))

;; (attach1 nlist (+ 2 2)) ; append without wrapping element to be added in a list
查看更多
登录 后发表回答