Search code examples
recursionschemeguile

How do I turn #<unspecified> into a number in guile scheme


I'm trying to get the hang of recursion in scheme. I put together a Fibinachi function and it keeps returning unspecified instead of a number. How do I make this function return a number and to unspecified?

(define (F n)
  (if (= n  0)
      0)
  (if (= n 1)
      1)
  (if (< n 2)
      (+
       (F (- n 1))
       (F (- n 2)))))

(display (F 5))
(newline)

The function returns

#<unspecified>

I'm using guile (GNU Guile) 2.0.13.


Solution

  • The issue here is that your code is:

    (begin
      (if a 1)
      (if b 2) 
      (if c 3))
    

    What is wrong with this? The value of that will be unspecified except if c is true.

    Why? The value of each if is unspecified when the condition is false. The begin returns the value of the last expression.

    Where did the begin come from you might ask as it didn't appear in my code? To make it easier every lambda and define contains an implicit begin which is why your code was even accepted for execution.

    You should use either nested ifs or a cond form:

    (if a 1 
        (if b 2 
            (if c 3)))
    
    (cond (a 1) 
          (b 2) 
          (c 3))