Here is the question:
Write a function (first-n-elements lst n), which returns a list containing only the first n elements of lst. For example, (first-n-elements '(1 2 3 4 5 6) 3) should return '(1 2 3). Your function should handle the case where n is greater than the length of the list (in which case it would return the entire list), and where n is 0 (should return '()).
My answer is:
(define (first-n-elements lst n)
(cond((null? lst) '())
((= n 0) lst))
((> n 0) (cons (+ (car lst) 1) (first-n-elements) (cdr lst) (- n 1))))
I know it’s wrong, please help
Part of the question says that if
nis 0, it should return'(). But what does your function do whennis 0?Also, think about the recursive case here (
> n 0). You’re currently returning theconsof four arguments:(+ (car lst) 1)(first-n-elements)(cdr lst)(- n 1)But
consonly takes two arguments. You have all the parts there, but they’re not quite put together right. What do you want to beconsing together?Also: why are you adding 1 to
(car lst)? That’s not going to work iflsthas something other than numbers in it.