Created
November 27, 2014 03:47
-
-
Save EmmanuelOga/e136114ce9afe7795dcf to your computer and use it in GitHub Desktop.
Balancing routine example from http://learnyouahaskell.com/ book.
This file contains 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
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