Skip to content

Instantly share code, notes, and snippets.

@sjoerdvisscher
Created July 19, 2011 23:14
Show Gist options
  • Save sjoerdvisscher/1093977 to your computer and use it in GitHub Desktop.
Save sjoerdvisscher/1093977 to your computer and use it in GitHub Desktop.
The Resumption monad is just the free monad.
-- The Resumption monad from [1] is just the free monad.
-- [1] http://tomasp.net/blog/comprefun.aspx
import Control.Monad.Free -- From http://hackage.haskell.org/package/free
import Control.Monad.Trans
import Control.Applicative
printLoop :: String -> Int -> a -> Free IO a
printLoop str count result = do
lift $ putStrLn str
if count == 1 then return result
else printLoop str (count - 1) result
cats :: IO String
cats = retract $ printLoop "meow" 3 "cat"
mzip :: Applicative f => Free f a -> Free f b -> Free f (a, b)
mzip (Pure a) (Pure b) = Pure (a, b)
mzip sa sb = Free $ mzip <$> step sa <*> step sb
where step (Pure r) = pure $ Pure r
step (Free f) = f
animalsSeq :: Free IO String
animalsSeq = do
c <- printLoop "meow" 2 "cat"
d <- printLoop "woof" 3 "dog"
return $ c ++ " and " ++ d
animalsPar :: Free IO String
animalsPar = do
(c, d) <- mzip (printLoop "meow" 2 "cat") (printLoop "woof" 3 "dog")
return $ c ++ " and " ++ d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment