Created
January 28, 2013 18:50
-
-
Save r00k/4658025 to your computer and use it in GitHub Desktop.
Kinda mind-blowing fibonacci-sequence-producing function.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn fib [n] | |
(take n (map first (iterate (fn [[a b]] [b (+ a b)]) [1 1])))) | |
(fib 5) => (1 1 2 3 5) |
You can do something similar in JS though it's not as pretty:
function allfibs(end) {
var x = 0, y = 1, count = 1;
yield 1;
while (count++ < end) {
[x,y] = [y,x + y];
yield y;
}
}
function fibs(x) {
return [ i for (i in allfibs(x)) ]
}
fibs(5) // [1,1,2,3,5]
Wouldn't be hard to write some library functions like take() to get the nth element etc.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The beauty of the solution:
is that the Fibonacci numbers are a sequence of all of the Fibonacci numbers rather than some function that calculates the nth Fibonacci number. Therefore, the way to interact with fibs is to just reach in and get what you want:
If you again want to get the value of the 100th Fibonacci number then just grab it again, Clojure will not calculate it again. I Fibonacci function is kinda cool, but all of the Fibonacci numbers is way cooler.