Getting the first n elements of a list in Common Lisp?

user12163 picture user12163 · Nov 12, 2009 · Viewed 12.7k times · Source

How would I get the first n elements of a list?

CL-USER> (equal (some-function 2 '(1 20 300))
                '(1 20))
T

I am absolutely certain this is elementary, but help a brother newb out.

Answer

Pillsy picture Pillsy · Nov 12, 2009

Check out the SUBSEQ function.

* (equal (subseq '(1 20 300) 0 2)
         '(1 20))
T

It may not be immediately obvious, but in Lisp, indexing starts from 0, and you're always taking half-open intervals, so this takes all the elements of the list with indices in the interval [0, 2).