Search code examples
schemefibonaccimit-scheme

MIT Scheme: Unspecified return value error


MIT Scheme: I was writing a function to calculate the nth term of the Fibonacci series (section 1.2.2 of SICP) but I am getting the error: Unspecified return value

(define (fib n) (
     define (fib-iter a b count) (
            if (= count n) a
            (fib-iter b (+ a b) (+ count 1)))
     (fib-iter 0 1 1))
)

Thanks for the help.


Solution

  • Your helper function fib-iter is missing a closing bracket at the end, with an extra closing bracket for fib. As a result, the line (fib-iter 0 1 1) gets included in fib-iter, and fib ends up containing no expressions to actually evaluate and return, hence the error ... no expression in body ....

    Here is what you want:

    (define (fib n)
      (define (fib-iter a b count)
        (if (= count n)
            a
            (fib-iter b (+ a b) (+ count 1))))    ; 1 closing bracket added here
      (fib-iter 0 1 1))                           ; 1 closing bracket removed here
    

    You might benefit from using some editors that match parentheses. For example, Dr. Racket highlights the function body that is contained within a set of parens if your cursor is active on either the opening or closing of said parentheses.