Question

I'm currently working on exercise 1.29 of SICP, and my program keeps giving me the following error:

+: expects type <number> as 2nd argument, given: #<void>; other arguments were: 970299/500000

Here's the code I'm running using racket:

  (define (cube x)
    (* x x x))

  (define (integral2 f a b n)
    (define (get-mult k)
      (cond ((= k 0) 1)
            ((even? k) 4)
            (else 2)))
    (define (h b a n)
      (/ (- b a) n))
    (define (y f a b h k)
      (f (+ a (* k (h b a n)))))
    (define (iter f a b n k)
      (cond ((> n k)
             (+ (* (get-mult k)
                   (y f a b h k))
                (iter f a b n (+ k 1))))))
    (iter f a b n 0))

(integral2 cube 0 1 100)

I'm guessing the "2nd argument" is referring to the place where I add the current iteration and future iterations. However, I don't understand why that second argument isn't returning a number. Does anyone know how to remedy this error?

Was it helpful?

Solution 2

You're missing an else clause in your iter procedure. Ask yourself: what should happen when (<= n k) ? It's the base case of the recursion, and it must return a number, too!

(define (iter f a b n k)
  (cond ((> n k)
         (+ (* (get-mult k)
               (y f a b h k))
            (iter f a b n (+ k 1))))
        (else <???>))) ; return the appropriate value

OTHER TIPS

"2nd argument" refers to the second argument to +, which is the expression (iter f a b n (+ k 1)). According to the error message, that expression is evaluating to void, rather than a meaningful value. Why would that be the case?

Well, the entire body of iter is this cond expression:

(cond ((> n k)
       (+ (* (get-mult k)
             (y f a b h k))
          (iter f a b n (+ k 1)))))

Under what circumstances would this expression not evaluate to a number? Well, what does this expression do? It checks if n is greater than k, and in that case it returns the result of an addition, which should be a number. But what if n is less than k or equal to k? It still needs to return a number then, and right now it isn't.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top