Buisson
Buisson

Reputation: 539

how to get N first element of a list

I want to make a function to get the N-th first element of a list.

For example :

>>(firsts 3 '(a b c d e))

return : (a b c)

I made that :

(define (firsts number lst)
  (let ((maliste '()))
        (if (equal? 0 number)
            maliste
            (and (set! maliste (cons (car lst) maliste)) (firsts (- number 1) (cdr lst))))))

But it doesn't work, I think I should use a let but I don't know how.

Thanks .

Upvotes: 1

Views: 1333

Answers (1)

Óscar López
Óscar López

Reputation: 235984

It's a lot simpler, remember - you should try to think functionally. In Lisp, using set! (or other operations that mutate state) is discouraged, a recursive solution is the natural approach. Assuming that the list has enough elements, this should work:

(define (firsts number lst)
  ; as an exercise: add an extra condition for handling the
  ; case when the list is empty before the number is zero
  (if (equal? 0 number)
      '()
      (cons (car lst)
            (firsts (- number 1) (cdr lst)))))

Upvotes: 3

Related Questions