Created
January 20, 2013 11:57
-
-
Save igrep/4578128 to your computer and use it in GitHub Desktop.
From "Learn you a Haskell for Great Good!" Simulation of Pole's tightrope walking by Either monad.
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
| module PoleEither where | |
| import Control.Monad.Error () | |
| import Data.List (intersperse) | |
| type Birds = Int | |
| type Pole = (Birds, Birds) | |
| landLeft :: Birds -> Pole -> Either String Pole | |
| landLeft n (left, right) = | |
| if balance < 4 | |
| then Right (left', right) | |
| else Left $ shoutBirdsNum "Too many birds! I can't stand!" right left' | |
| where | |
| left' = left + n | |
| balance = abs $ left' - right | |
| landRight :: Birds -> Pole -> Either String Pole | |
| landRight n (left, right) = | |
| if balance < 4 | |
| then Right (left, right') | |
| else Left $ shoutBirdsNum "Too many birds! I can't stand!" right' left | |
| where | |
| right' = right + n | |
| balance = abs $ left - right' | |
| shoutBirdsNum :: String -> Birds -> Birds -> String | |
| shoutBirdsNum cause l r = concat $ intersperse "\n" msg | |
| where | |
| msg = | |
| [cause | |
| ," Left: " ++ show l | |
| ," right: " ++ show r] | |
| banana :: Pole -> Either String Pole | |
| banana (l, r) = Left $ shoutBirdsNum "Oh, banana! slip down!" l r | |
| routine :: Either String Pole | |
| routine = do | |
| start <- return (0,0) | |
| first <- landLeft 2 start | |
| second <- landRight 2 first | |
| banana second |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment