chanpkr
chanpkr

Reputation: 915

fibonacci function in scheme

I'm trying to convert a fibonacci function from python to scheme,

def fib(n):
    if n == 1:
        return 0
    if n == 2:
        return 1
    return fib(n-1) + fib(n-2)

to

(define (fib n)
    (if (= n 1)
         0)
    (if (= n 2)
         1)
    (+ fib (- n 1)) (fib (- n 2)))

I get error here because apparently scheme requires an else statement. However, as a novice scheme learner, I can't figure out how to make it with an else statement. Can anyone help? thanks.

Upvotes: 2

Views: 2693

Answers (2)

sve
sve

Reputation: 4356

Try

(define (fib n)
    (if (= n 1)
         0
         (if (= n 2)
             1
             (+ (fib (- n 1)) (fib (- n 2))))))

The syntax is:

(if predicate consequent alternative)

such as

(if (> 3 2) 'yes 'no)

But I would recommend you to use cond in your case

Upvotes: 1

Óscar López
Óscar López

Reputation: 236004

In some Scheme interpreters (in particular: in Racket) all if expressions must have two parts: consequent and alternative (the else part). So to fix your code, you should nest the if expressions like this (and notice the recommended way to indent and close the parentheses):

(define (fib n)
  (if (= n 1)
      0
      (if (= n 2)
          1
          (+ (fib (- n 1)) (fib (- n 2))))))

But to tell the truth, when there are more than two conditions, you should use cond instead of nesting ifs, it'll be easier to write and easier to read:

(define (fib n)
  (cond ((= n 1) 0)
        ((= n 2) 1)
        (else (+ (fib (- n 1)) (fib (- n 2))))))

For completeness' sake: for those cases when you really, really want to use an if without an else part, you can use when. And a bit of nitpicking: the usual way to define fibonacci is to return 0 if n is 0, and to return 1 if n is 1; as it is your implementation will return incorrect results.

Upvotes: 4

Related Questions