i working on problem 9 of project euler, , have question best way extract maybe value inside monad. problem asks find 'a', 'b', 'c' satisfy:
- a^2 + b^2 = c^2
- a + b + c = 1000
i have written following code solves problem:
problem9 :: (integral a) => -> [(a, a, a)] problem9 n = <- [1..n] b <- [1..a] c <- fromjustm (findc b) guard (a + b + c == n) return (a, b, c) 'c' can computed analytically, but, since may not exist, return maybe value.
findc :: (integral a) => -> -> maybe findc b = ... (implementation) ... to extract maybe value inside list monad, have created following function:
fromjustm :: (monad m) => maybe -> m fromjustm (just a) = return fromjustm nothing = fail "" it seems should common operation, there standard library function this, or there more idiomatic way it?
fail not monadic operation; it's in monad type class because of historic accident / hide dirty error handling.
a more proper class monadplus, or rather applicative correspondent alternative. fail translates empty. that, signature should in fact be
fromjustm' :: alternative m => maybe -> m asum :: (foldable t, alternative f) => t (f a) -> f which fits bill: maybe foldable.
c <- asum $ pure <$> findc b arguably, not in fact readable.
you can achieve goal easier writing
c <- pure $ findc b this again use fail method: pattern-match failure in do block calls implicitly.
Comments
Post a Comment