Phil
Phil

Reputation: 33

Creating a list of Fibonacci numbers in Scheme?

I've made a basic program that output Fibonacci sequence for whatever length "n". Here's the code I have:

(define (fibh n)
  (if (< n 2)
      n
      (+ (fibh (- n 1)) (fibh (- n 2)))))

(define (fib n)
  (do ((i 1 (+ i 1)))
      ((> i n))
    (display (fibh i))))

It will output, for example, 112358.

What I want is a list such as (1 1 2 3 5 8).

Any explanation how to do this would be greatly appreciated.

Upvotes: 3

Views: 5277

Answers (2)

user448810
user448810

Reputation: 17866

Petite Chez Scheme Version 8.3
Copyright (c) 1985-2011 Cadence Research Systems

> (define (fib n)
    (let loop ((n n) (f2 1) (f1 1) (fs (list)))
      (if (zero? n) (reverse fs)
        (loop (- n 1) f1 (+ f2 f1) (cons f2 fs)))))
> (fib 50)
(1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584
 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811
 514229 832040 1346269 2178309 3524578 5702887 9227465
 14930352 24157817 39088169 63245986 102334155 165580141
 267914296 433494437 701408733 1134903170 1836311903
 2971215073 4807526976 7778742049 12586269025)

Upvotes: 2

Fred Foo
Fred Foo

Reputation: 363627

(map fibh '(1 2 3 4 5 6))

would do the trick. If you don't want to enumerate the integers by hand, then implement a simple recursive function that will do that for you, like:

(define (count i n)
  (if (= i n)
    '()
    (cons i (count (+ i 1) n))))

(Note: this is not tail-recursive, but with that algorithm to compute the Fibonacci numbers, that's not your prime concern.)

Upvotes: 6

Related Questions