Raymond
Raymond

Reputation: 1

Racket "first: expects a non-empty list; given: empty"

I was writing some code that outputs a list of factorials given a list of natural numbers. So (list 1 4 3) would give (list 1 24 6). Currently Racket is giving me the error "first: expects a non-empty list; given: empty" when on the line with the (cons ......). I used the debugger to check and the code never reaches empty, is there a way to fix this?

(define (factorialize arr)
 (cond
    [(empty? arr) empty]
    [else (cons (factorial (first arr)) (factorialize (factorial (first (rest arr)))))]))

;;helper function
(define (factorial num)
  (cond
    [(= 0 num) 1]
    [else (* num (factorial (- num 1)))]))

Upvotes: 0

Views: 714

Answers (1)

Óscar López
Óscar López

Reputation: 235994

The recursive step isn't right, why do you call (factorialize (factorial (first (rest arr))))? that's trying to apply factorialize on the result of factorial, which is a number and not the list expected by factorialize. You just need to advance the recursion by invoking the procedure on the rest of the list! Try this:

(define (factorialize arr)
  (cond
    [(empty? arr) empty]
    [else (cons (factorial (first arr))
                (factorialize (rest arr)))]))

FYI, a simpler and more idiomatic implementation would use the built-in map higher-order procedure:

(define (factorialize arr)
  (map factorial arr))

Either way, it works as expected:

(factorialize '(1 4 3))
=> '(1 24 6)

Upvotes: 1

Related Questions