Rita Pereira
Rita Pereira

Reputation: 61

Add lists to a list lisp

I'm new to Lisp and I'm having trouble figuring out how I add a list to another list. I start with an empty list, and I have to add new lists, each containing three elements. For example,

(add '(1 2 3) '())

would return ((1 2 3)) [let's call it new-list], and adding a new list to this new one, for example

(add '(4 5 6) new-list)

would return ((1 2 3) (4 5 6)) or ((4 5 6) (1 2 3))

I've tried a few different ways, but so far the closest I've come up was ((((1 2 3)) (4 5 6)) (7 8 9))

I was using something like this:

(defun add (lst new-let) (if (null lst) '() (setf new-lst (cons new-lst (cons lst '()))))

Upvotes: 0

Views: 3812

Answers (3)

Sylwester
Sylwester

Reputation: 48745

You being new to LISP I'd like to give you an alternative to the accepted answer.

Lists are singly linked list chains. Such structure allows for adding and removing in front to be a constant time operation while adding or removing something from the end would take as many turns as there are elements in the list in both time and space (it will have to recreate the list structure on it's way).

(defun add (element list)
  (cons element list))

This looks very familiar.. It's actually just a wrapper to cons. So lets imagine you have a practical application where you'd like to use add, but needed the elements in the order in your question. One way to do it would then be to finish up first (add whats to add), then do one reverse or nreverse (if every element was made in your function and mutation won't matter for the outside)..

(defun fetch-all (num-elements thunk &optional acc)
  (if (zerop num-elements)
      (nreverse acc)
      (fetch-all (- num-elements 1) thunk (add (funcall thunk) acc)))); add == cons

Upvotes: 0

JB.
JB.

Reputation: 42094

The way I read it, your requirement is exactly cons (non destructive) or push (destructive).

Upvotes: 1

Broseph
Broseph

Reputation: 1753

Have you tried :

(defun add (thing lst) (append lst (list thing)))

I haven't tried this with Common Lisp as I am more of a Scheme kind of guy, bu I think it would work.

Upvotes: 2

Related Questions