Project Euler With Clojure

PUBLISHED ON 2019-06-27

I’ve been trying to expand my programming lately by learning some new languages, specifically ones that fill niches that Python doesn’t. These have included Rust, Go, and Clojure, but I think I’m having the most fun with Clojure (though both Rust and Go are also great, they’re just not as much fun.)


(Spoiler Warning: This post contains my solution for Project Euler Problem #2. If you don’t want to be spoiled on a potential strategy for the answer, you should find your own solution before reading the rest of this post.)


As an example, here’s a bit of Clojure I wrote to solve Project Euler problem #2:

(reduce
 +
 (filter
  even?
  (loop [result [1 2]]
    (let [z (reduce + (take-last 2 result))]
      (if (> z 4000000)
        result
        (recur 
          (conj result z))))))

This gives the right answer, but its not exactly great code, is it? Let’s try and improve things a bit.

First thing that jumps out is the lack of reusability. We can fix that by putting the whole thing into a function:

 (defn fib-euler
   "Returns the sum of all the even fibonacci numbers up to the limit
   provided"
   [limit]
   (reduce
    +
    (filter
     even?
     (loop [result [1 2]]
       (let [z (reduce + (take-last 2 result))]
         (if (> z limit)
           result
           (recur 
             (conj result z))))))))

So now we’ve got a reusable function for our problem, and we’ve even added some documentation as well as making the limit a parameter we can pass to the function.