Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returns the first n of list

Tags:

list

scheme

How to return the first n elements of a list? Here's what I have:

(define returns(lambda (list n)
 (cond ((null? list) '())
 (((!= (0) n) (- n 1)) (car list) (cons (car list) (returns (cdr list) n)))
        (else '()))))

Examples:

(returns '(5 4 5 2 1) 2)
(5 4)

(returns '(5 4 5 2 1) 3)
(5 4 5)
like image 311
New Avatar asked Dec 16 '22 14:12

New


1 Answers

You're asking for the take procedure:

(define returns take)

(returns '(5 4 5 2 1) 2)
=> (5 4)

(returns '(5 4 5 2 1) 3)
=> (5 4 5)

This looks like homework, so I guess you have to implement it from scratch. Some hints, fill-in the blanks:

(define returns
  (lambda (lst n)
    (if <???>                     ; if n is zero
        <???>                     ; return the empty list
        (cons <???>               ; otherwise cons the first element of the list
              (returns <???>      ; advance the recursion over the list
                       <???>))))) ; subtract 1 from n

Don't forget to test it!

like image 154
Óscar López Avatar answered Feb 15 '23 16:02

Óscar López