I'm learning Clojure and solved Project Euler #1, I'd like to have my code reviewed on all aspects and have one specific question. This is also my first Functional Programming language, I have however used some form of FP in Java and Python before.
Task: Multiples of 3 and 5
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
My solution
(ns euler)
(defn is-divisible-by?
[x divisor]
(zero? (mod x divisor)))
(->> (range 1000)
(filter #(or (is-divisible-by? % 3) (is-divisible-by? % 5)))
(reduce +)
(println))
My additional question is whether the filter part can be written more succintly as I'm duplicating code right now while all I need to actually to is dos ome operation on 3
and 5
.
1 Answer 1
Good to extract the method is-divisible-by?
. Ending with a question mark indicates a predicate, so is-
prefix is not necessary. I think it is somewhat more readable if the divisor comes before the value, but that might be personal preference.
(defn divisible-by?
[divisor x]
(zero? (mod x divisor)))
Furthermore, if you provide a conditional in the fn
to reduce
you don't need a filter
. It is debatable if it is more readable, but it is shorter and saves one walk over the collection I think (although I measure no difference in performance between the if
-statement and the filter
). Also there is no need for parentheses around println
:
(->> (range 1000)
(reduce #(if (or (divisible-by? 5 %2)
(divisible-by? 3 %2))
(+ %1 %2)
%1))
println)
You can get inspired by other answers on the projecteuler thread for question 1.
Explore related questions
See similar questions with these tags.