Creating a list of Fibonacci numbers in Scheme?

I have created a basic program that outputs the Fibonacci sequence for any length "n". Here is 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 outputs, for example 112358

.

I need a list for example (1 1 2 3 5 8)

.

Any explanation on how to do this would be greatly appreciated.

+3


source to share


2 answers


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

      

would do the trick. If you don't want to manually enumerate integers, then implement a simple recursive function that does it for you, like this:



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

      

(Note: this is not tail recursion, but with this algorithm for calculating Fibonacci numbers, this is not your main problem.)

+6


source


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)

      



+2


source







All Articles