I've been teaching myself basic haskell this week in order to be able to better read literature about functional programming (about 80% of which in haskell by my completely off-the-cuff statistic). Just as a check to make sure I got the basic concepts, here is how I answered Project Euler 1.
divisible :: Integral a => a -> a -> Bool divisible x y = mod y x == 0 -- do any of the predicates match a value any' :: [a -> Bool] -> a -> Bool any' predicates match = any ($ match) predicates euler1 :: Integral a => [a] -> a euler1 xs = sum . filter (any' [divisible 3, divisible 5]) xs euler1' = euler1 [1..999]
I opted to describe how the answer is defined (as seems to be the way FP works) as opposed to find a faster solution, as this was an exercise in idiomatic FP and haskell.
Since this is supposed to be a practice in idiomatic haskell, point free seems to be the way to go:
-- with the same type definitions divisible = ((==) 0 .) . flip mod any' = flip (any . flip id) euler1 = sum . filter $ any' [divisible 3, divisible 5]
The main purpose of this review is this: which definition of each of these functions is the most idiomatic haskell? Along those lines, this is not supposed to be reinventing-the-wheel, and if a
Prelude or stdlib solution to
any' exists, they should be replaced with the stdlib version.
I admit that tools were used in the process of creating the pointfree version. With
divisible I think I fully understand the composition (
f . . g ===
f ( g ( arg, arg ) )), but I'd be fecetious in saying I fully understood the pointfree formulation of
any'. That may effect the best solution for me, but I'm interested mostly in idiomatic, readable (to more veteran haskellers) code.