0

I'm new to scheme language and trying to execute this code that calculating the n'th Fibonacci series using an internal function.

for some reason it doesn't work for me and i would like to get some help. Thank you.

    (define fibo (lambda (n)
      (define (helperFunction n n1 a_n)
        (begin
        (display a_n)
        (newline)
        (if (> n 1)
        (helperFunction (- n 1) (+ n1 a_n) n1))))
       (helperFunction n 1 1)))

1 Answer 1

1

First off, why do you use the long version in fibo and the short version in helperFunction? eg.

(define long-version (lambda (arg) arg))
(define (short-version arg) arg)

These are the same. Books often use the long version to point out that functions are values and the names are bindings just as with variables, but its practical to use the short version when you already have started with it.

a begin that wraps the contents of a function is unnecessary since all functions have explicit begin.

An if where you only have a test and a then clause will return a implementation chosen value when the test is false. I tend to use the symbol undefined to not get any surprises on what the undefined value is.

You need to indent your code properly. I use DrRacket and press CTRL+I. With these I get your code like this:

(define (fibo n)
  (define (helperFunction n n1 a_n)
    (display a_n)
    (newline)
    (if (> n 1)
        (helperFunction (- n 1) (+ n1 a_n) n1)
        'undefined))
  (helperFunction n 1 1))

So lets try this:

(fibo 1) ; ==> undefined

That makes sense from looking at the code. It's hardly correct but it does what it has been instructed to do. What if it was 2?

(fibo 2) ; ==
(helperFunction 1 2 1) ==> undefined

I think your problem is that instead of undefined you should have n1 as the result.

(define (fibo n)
  (define (helperFunction n n1 a_n)
    (display a_n)
    (newline)
    (if (> n 1)
        (helperFunction (- n 1) (+ n1 a_n) n1)
        n1))
  (helperFunction n 1 1))

A note on the function. A standard fibonacci goes like 0,1,1,2,3,5 and the function is usually zero indexed such that:

(fib 0) ; ==> 0
(fib 1) ; ==> 1
(fib 10) ; ==> 55
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! , your notes are absolutely correct. but still when im trying to execute the code, it marks the last line and writes: "define: expected only one expression for the function body, but found 1 extra part". any idea?
@Barakmichaeli Scheme has no such restrictions. Are you using a student language? They tend to be restrictive. If so you might want to remove the two lines that create output.
Thank you (: Just changed to standard language.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.