Skip to content

Instantly share code, notes, and snippets.

@igrep
Created January 20, 2013 11:57
Show Gist options
  • Select an option

  • Save igrep/4578128 to your computer and use it in GitHub Desktop.

Select an option

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.
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