-
-
Save lenary/bf90bfab852d9b9261dc8b8d7ad4e9c1 to your computer and use it in GitHub Desktop.
Haskell pattern question
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- In `f` we want to keep piping (part of) the result of one function into | |
-- another, and stop as soon as something fails | |
f :: [A] -> Either String (B, [A]) | |
f xs = | |
case f1 xs of | |
Left s -> Left s | |
Right (res1, xs') -> | |
case f2 xs' of | |
Left s -> Left s | |
Right (res2, xs'') -> | |
case f3 xs'' of | |
Left s -> Left s | |
Right (res3, xs''') -> | |
Right (B res1 res2 res3, xs''') | |
-- This is exactly `Monad (Either String)` | |
f' xs = do (res1, xs') <- f1 xs | |
(res2, xs'') <- f2 xs' | |
(res3, xs''') <- f3 xs'' | |
return (B res1 res2 res3, xs''') | |
-- In `g` we want to keep trying different functions with the same input | |
-- until something succeeds, and then stop | |
g :: [A] -> Either String (B, [A]) | |
g xs = | |
case g1 xs of | |
Right (res1, xs') -> Right (res1, xs') | |
Left s -> | |
case g2 xs of | |
Right (res2, xs') -> Right (res2, xs') | |
Left s -> | |
case g3 xs of | |
Right (res3, xs') -> Right (res3, xs') | |
Left s -> Left s | |
-- this is more complicated, lemme remember what it's called, but it's also possible. | |
-- Maybe this is `Alternate (Either String)` but I cannot remember the name immediately. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment