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条回答
smile是对你的礼貌
2楼-- · 2020-02-04 02:54

Cons-ing at the end of a list can be achieved with this function:

(defun cons-last (lst x)
  (let ((y (copy-list lst))) (setf (cdr (last y)) (cons x nil)) y))

;; (cons-last nlist (+ 2 2))
查看更多
啃猪蹄的小仙女
3楼-- · 2020-02-04 02:59

You could use append, but beware that it can lead to bad performance if used in a loop or on very long lists.

(append '(1 2 3) (list (+ 2 2)))

If performance is important, the usual idiom is building lists by prepending (using cons), then reverse (or nreverse).

查看更多
我命由我不由天
4楼-- · 2020-02-04 03:01

If you want to add an item onto the end of a given list without changing that list, then as previously suggested you can use a function like

(defun annex (lst item)
  "Returns a new list with item added onto the end of the given list."
  (nconc (copy-list lst) (list item)))

This returns a new extended list, while preserving the input list. However, if you want to modify the input list to include the added item, then you can use a macro like

(define-modify-macro pushend (item)
  (lambda (place item)
    (nconc place (list item)))
  "Push item onto end of a list: (pushend place item).")

Pushend operates like push, but "pushes" the item onto the end of the given list. Also note the argument order is the reverse of push.

查看更多
够拽才男人
5楼-- · 2020-02-04 03:07

If you are trying to add two lists for example (1 2 3) + (1 2 3) here is the code (recursive)

(defun add-to-all (x y)
    (T (appendl (+ (first x) (first y)) (add-to-all (tail x) (tail y)) ))
)

If you are trying to add an item to the end of the second list, for example 3 + (1 2 3)

(defun add-to-all (x y)
  (cond ((null? y) nil)
    (T (appendl (+ (first x) (first y)) (add-to-all (tail x) (tail y)) ))
  )
)
查看更多
Rolldiameter
6楼-- · 2020-02-04 03:09

(append l (list e)) ; e is the element that you want to add at the tail of a list

查看更多
混吃等死
7楼-- · 2020-02-04 03:10

You haven't specified the kind of Lisp, so if you use Emacs Lisp and dash list manipulation library, it has a function -snoc that returns a new list with the element added to the end. The name is reversed "cons".

(-snoc '(1 2) 3) ; (1 2 3)
查看更多
登录 后发表回答