Project Euler #1 using Haskell
import Data.Set
euler :: Int
euler = sum [ x | x <- nums ]
where
nums = Data.Set.toList (Data.Set.union (Data.Set.fromList [3,6..999])
(Data.Set.fromList [5,10..999]))
I am learning Haskell and hope you don't mind me asking this. Is there a nicer way to get a list holding all natural numbers below one thousand that are multiples of 3 or 5? (Eg with zip or map?)
Edit:
import Data.List
euler :: Int
euler = sum (union [3,6..999] [5,10..999])
Thanks for your help, guys.
使用列表理解:
sum [x | x <- [1..999], x `mod` 3 == 0 || x `mod` 5 == 0]
你也可以使用硬编码版本:
sum $ [3, 6 .. 999] ++ [5, 10 .. 999] ++ [-15, -30 .. -999]
这会给你你要求的清单:
filter (x -> (x `mod` 3 == 0) || (x `mod` 5 == 0)) [1..999]
链接地址: http://www.djcxy.com/p/80422.html
上一篇: C vs Haskell Collatz猜想速度比较
下一篇: 项目欧拉#1使用Haskell