Jes' Codex

jes5199 of blog
Posts I Like

I realized that I’ll never be able to finish inventing a programming language if I don’t learn a LISP first.

So I’ve been playing with Project Euler with a Clojure repl, and … well, it’s not ruby and it’s not Haskell.

But it has a lot of lazy data structures, so I decided to pretend I was writing Haskell anyway and see what happens.

Here’s a Haskell-ish way to generate the fibonacci numbers:

let fib = 1 : 1 : (map (uncurry (+)) (zip (drop 1 fib) fib))

So I decided to port it directly to Clojure. It wouldn’t be possible to do in a language that didn’t have lazy sequences, but I was able to do it in Clojure pretty straightforwardly. Here’s a before-and-after, so you can see how the two definitions relate:

 let  fib    =            1:1 : (map (uncurry      (+)) ( zip                     (drop 1  fib )  fib    ) )
(defn fib [] ( lazy-cat [ 1 1 ] (map (partial apply + ) ( partition 2 (interleave (drop 1 (fib)) (fib) ) ) ) ) )


Gosh, you know, after a while you don’t even see those parentheses. 

Let’s see how it works!

Here’s Haskell, for reference:

Prelude> take 30 fib
[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]

And the Clojure:

user=> (take 30 (fib))
java.lang.OutOfMemoryError: Java heap space
(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

Well, there you have it.