KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I have started looking at the project Euler site as a way to learn Haskell, and improve my Python and Ruby. I think the Haskell and Python versions are ok, but I'm sure there must be a cleaner way for Ruby. This is not about how can I make one language look like another one. This is Problem 1 : Q: Add all the natural numbers below one thousand that are multiples of 3 or 5. Haskell: sum [ x | x <- [1..999], mod x 3 == 0 || mod x 5 == 0 ] Python: sum ( [ x for x in range(1,1000) if x % 3 == 0 or x % 5 == 0 ] ) Ruby: (1..999) . map {|x| x if x % 3 == 0 || x % 5 == 0 } . compact . inject(:+) They all give the same answer. OK, so Python can become: sum ( x for x in range(1,1000) if x % 3 == 0 or x % 5 == 0 ) it is now a generator (a good thing as we are not storing the list) but even more fun is: sum( set(range(0,1000,3)) | set(range(0,1000,5)) ) For some reason I was looking at this again and tried a summation approach which should be constant time. In Python 3: def step_sum(mn,mx,step): amax = mx - (mx - mn) % step return (mn + amax) * ((1 + ((amax - mn) / step)) / 2) step_sum(3,999,3) + step_sum(5,999,5) - step_sum(15,999,15) Ruby can become: (1..999) . select {|x| x % 3 == 0 || x % 5 == 0} . inject(:+) or (1..999) . select {|x| x % 3 == 0 or x % 5 == 0} . reduce(:+) I am presuming as unlike map , select doesn't produce 'nul' and therefore there is no need to call compact . nice. Haskell can also be: let ƒ n = sum [0,n..9
Tags (comma-separated)
Save Edits
Cancel