0

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

klee17
  • 13
  • 8

1 Answers1

0

There are a couple of errors in your solution:

  • In the second condition, you forgot to cons the current value - remember, we're recursively building a list as an answer, and we must use cons to do so
  • The second and third conditions should use 0 and not 1. Otherwise the procedure will fail when n equals zero
  • The base case, when n equals zero, should return the empty list - otherwise the output list will not be properly constructed

With 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)
Óscar López
  • 232,561
  • 37
  • 312
  • 386