Skip to content

Instantly share code, notes, and snippets.

@EmmanuelOga
Created November 27, 2014 03:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EmmanuelOga/e136114ce9afe7795dcf to your computer and use it in GitHub Desktop.
Save EmmanuelOga/e136114ce9afe7795dcf to your computer and use it in GitHub Desktop.
Balancing routine example from http://learnyouahaskell.com/ book.
import Control.Monad
import Control.Monad.State
type Birds = Int
type Pole = (Birds, Birds)
type Balance = Either String Pole
birdLand :: Pole -> Balance
birdLand pole@(left, right) = if balanced
then return pole
else Left "Lost balance!"
where balanced = abs (left - right) < 4
landLeft :: Birds -> State Pole Balance
landLeft n = state (\(left,right) -> let newpole = (left + n, right) in (birdLand newpole, newpole))
landRight :: Birds -> State Pole Balance
landRight n = state (\(left,right) -> let newpole = (left, right + n) in (birdLand newpole, newpole))
routine :: State Pole Balance
routine = do
landLeft 3
landRight 2
landLeft 6
main = do
print $ runState routine (0, 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment