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)
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With