Is this an idiomatic Clojure?

I started doing Project Euler with Clojure, as the first blow in learning Clojure. I solved the first task:

Find the sum of all multiples of 3 or 5 below 1000.

I previously solved it in Python:

sum(i for i in xrange(1000) if i%3==0 or i%5==0) 

This is my first attempt at Clojure:

 (reduce + (filter (fn [x] (or (= 0 (mod x 3)) (= 0 (mod x 5)))) (range 1000))) 

I am really surprised at how well he is brought to the end, but I am sure that this is due to my style and ignorance of Clojure idioms.

What would an idiomatic version of this Clojure code look like?

+7
source share
3 answers

Here is how I did it:

 (apply + (filter #(or (zero? (mod % 3)) (zero? (mod % 5))) (range 1000))) 

What makes my solution a little more idiomatic is using a macro of anonymous functions, #(...) and zero? fn

Your decision is different , but how good !

BTW - solving problems with Euler is a great way to learn a new language - you cannot get everything from the book.

Edit:

I decided to provide another solution that is more appropriate for your version of Python (not a very pretty IMO).

 (apply + (for [i (range 1000) :when (or (zero? (mod i 3)) (zero? (mod i 5)))] i)) 
+8
source

Another version:

 (defn sum-of [n] (reduce + (range n 1000 n))) (+ (sum-of 3) (sum-of 5) (- (sum-of 15))) 
+8
source

I like trying to solve the general solution for Project Euler projects, so here is my general solution:

 (defn sum-multiples [nums lim] (reduce + (filter (fn [x] (some identity (map #(zero? (mod x %)) nums))) (range lim)))) 

and then just call:

 (sum-multiples [3 5] 1000) 
0
source

All Articles