List comprehension in Haskell, Python and Ruby

前端 未结 5 984
天命终不由人
天命终不由人 2021-01-01 21:26

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 the

5条回答
  •  死守一世寂寞
    2021-01-01 21:54

    Try this for Ruby:

    (1..999).select {|x| x % 3 == 0 or x % 5 == 0}.reduce(:+)
    

    Or a little different approach:

    (1..999).reduce(0) {|m, x| (x % 3 == 0 or x % 5 == 0) ? m+x : m }
    

提交回复
热议问题