Joesph
Joesph

Reputation: 71

Get the Nth element in a List as a List instead of a number in LISP?

Let's say you have

(setq list '(1 2 3 4 5))

when using Nth to return the first element, the result is a number:

(nth 0 list)
Result: 1

Is there a way to get the result back as a List or convert result to list? Such as:

Result: (1)

Upvotes: 1

Views: 657

Answers (1)

sds
sds

Reputation: 60004

One can always turn any object to a list using the list function:

(defparameter *list* '(1 2 3 4 5))
(list (nth 0 *list*))
==> (1)

If, however, you are looking to get the slice of the argument that contains the number, you need to realize that it is impossible without modifying the argument *list*:

(defparameter *tail* (nthcdr 2 *list*))
*tail*
==> (3 4 5)

The following truncates both *tail* and *list*:

(setf (cdr *tail*) nil)
*tail*
==> (3)
*list*
==> (1 2 3)

Upvotes: 3

Related Questions