the purpose of this code is to remove and return the first N part of a list X
{define (grab x n)
(cond
[(< (len x) n) x]
[(> n 1)((car x) (grab(cdr x) (- n 1)))]
[(= n 1)(car x)]
)}
it currently just returns the above error
There are a couple of errors in your solution:
cons
the current value - remember, we're recursively building a list as an answer, and we must use cons
to do so0
and not 1
. Otherwise the procedure will fail when n
equals zeron
equals zero, should return the empty list - otherwise the output list will not be properly constructedWith all the above fixes in place, the procedure will work:
(define (grab x n)
(cond
[(< (len x) n) x]
[(> n 0) (cons (car x) (grab (cdr x) (- n 1)))]
[(= n 0) '()]))
As a side note, you're basically implementing the take
procedure, if that's available in your interpreter (except that take
will raise an error if n
is greater than the lists' length):
(take '(1 2 3 4 5) 3)
=> '(1 2 3)