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

Viewed 15282

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.

7 Answers

Recursive:

(defun first-n (list n)
  "Returns the first n elements of the list."
  (when (not (zerop n))
    (cons (first list) (first-n (rest list) (1- n)))))

(first-n '(a b c d e) 3)        ;(A B C)

With loop:

(defun first-n-loop (list n)
  "Returns first n elements of the list."
  (loop for i below n
     collect (nth i list)))

(first-n-loop '(a b c d e) 3)       ;(A B C)

Tinkering with the core CL functionalities:

(defun first-n (n list)
  "Returns the first N elements of the LIST."
  (butlast list (- (list-length list) n)))

(first-n 2 '(a s d f g))        ;(A S)
(defun pncar (n L)
  (setq L_ (list (nth 0 L)))
  (setq i 0)
  (if (and (< n 1) (< n (length L)))
    (setq L_ '())
    (repeat (- n 1) (progn
                      (setq i (+ i 1))
                      (if (/= nil (nth i L))
                        (setq L_ (append (list (nth i L)) L_))
                        (setq L_ '())
                        )
                      )
      )
    )
  (setq L_ (reverse L_))
  )

Examples:

(pncar 0 '(0 1 2 3))
    nil
(pncar 1 '(0 1 2 3))
    (0)
(pncar 2 '(0 1 2 3))
    (0 1)
(pncar 3 '(0 1 2 3))
    (0 1 2)
(pncar 4 '(0 1 2 3))
    (0 1 2 3)
(pncar 5 '(0 1 2 3))
    nil

(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'.

Related