The second solution will run indefinitely:
(defn e2 [limit]
(filter #(and (< % limit)
(zero? (mod % 2)))
fibs))
Using a predicate in the filter function of "< limit and mod 2 == 0" does not work as the fibs sequence is evaluated even after the terms in the sequence become greater than the limit (all it means is that every term above the limit is filtered out). Replacing the limit check with take-while would fix this.The third solution is also broken, it works fine for small values of n but enter a large number such as is given in the problem and you quickly run out of stack. Replacing the recursive call with recur will enable tail-call optimisation and give your stack a lot more breathing room.
I recommend the clojure-euler wiki for more reliable examples of good clojure code :)
So, yes its a learning process. I'm updating the post. Thanks again for your comments.
The difference is thus visible to the programmer and can be controlled with type hints.
nice ;)
Actually, on serious note, a great way to compare if your clojure code looks anything like it should.
> (range 1 (- limit 1))
this is wrong, it should be: (range 1 limit)
which will produce: (1 2 3 ... 999)
My old 32 bit machine died and the original (crappy) C solution now segfaults immediately, and was much slower.
Anyway, calculating and summing all the fibonacci numbers in less than half a millisecond is pretty cool.