views:

275

answers:

4

The title says it all, really. 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.

Kisses and hugs.

+12  A: 

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 the you're always taking half-open intervals, so this takes all the elements of the list with indices in the interval [0, 2).

Pillsy
A: 

Had to download a lisp command line... but:

(defun head-x (a b)
   (loop for x from 1 to a 
         for y = (car b) do 
            (setq b (cdr b)) 
         collect y))

so:

(head-x 2 '(a b c d))
  '(a b)
beggs
Just use `(loop :repeat a :for x :in b :collect x)` as your function body. Much simpler.
Pillsy
Thanks... been years since I actually did any lisp. Thought it be fun to answer a question!
beggs
+3  A: 

The above answer is of course perfectly correct, but note that if you're using this just to compare against another list, it would be more performance-efficient to walk both lists in-place, rather than consing up a new list just to compare.

For example, in the above case, you might say:

(every #'= '(1 20 300) '(1 20))
=> t

Love,

Ken
A: 

(butlast '(1 20 300) (- (list-length '(1 20 300)) 2))

Should be made into a function/macro.

P.S. This page might be useful. See function 'extrude'.

Definitely not a good idea to compute the length of a list for getting some elements from the front. Unlispy!
Rainer Joswig
Mmh, agreed. Bad idea.