Hello,

Am 19.10.2008 um 17:56 schrieb Lauri Oherd:

There is also a faster way to calculate fibonacci numbers in Clojure
(code taken from from
http://en.wikibooks.org/wiki/Clojure_Programming#Lazy_Fibonacci):

(defn fib-seq []
((fn rfib [a b]
      (lazy-cons a (rfib b (+ a b))))
   0 1))

user=> (time (take 38 (fib-seq)))
"Elapsed time: 0.032965 msecs"
(0 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)

This timing is wrong. Since take returns a lazy sequence
you only get the timing for the call to take. The sequence
is forced later on when the Repl prints it.

The correct way is to force the evaluation with doall.

  user=> (time (take 38 (fib-seq)))
  "Elapsed time: 0.055 msecs"
  ...
  user=> (time (doall (take 38 (fib-seq))))
  "Elapsed time: 0.3 msecs"
  ...

Sincerely
Meikel

Attachment: smime.p7s
Description: S/MIME cryptographic signature

Reply via email to