Created
February 11, 2016 01:35
-
-
Save adbrowne/27342cd83a412e040647 to your computer and use it in GitHub Desktop.
Church encoded free monads vs not
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
-- runs fast | |
{-# LANGUAGE DeriveFunctor #-} | |
{-# LANGUAGE FlexibleContexts #-} | |
{-# LANGUAGE TemplateHaskell #-} | |
module Main where | |
import Control.Monad | |
import Control.Monad.Free.Church | |
import Control.Monad.Free.TH | |
data DslCmd next = | |
GetValue' | |
Int | |
(Int -> next) | |
deriving (Functor) | |
makeFree ''DslCmd | |
type DslCmdM = F DslCmd | |
myProgram :: DslCmdM [Int] | |
myProgram = loop [0..1000000] | |
where loop = mapM getValue' | |
runCmd :: DslCmd (IO a) -> IO a | |
runCmd (GetValue' v n) = n (2 * v) | |
main :: IO () | |
main = do | |
r <- iterM runCmd myProgram | |
print $ sum r | |
return () |
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
-- runs really slow | |
{-# LANGUAGE DeriveFunctor #-} | |
{-# LANGUAGE FlexibleContexts #-} | |
{-# LANGUAGE TemplateHaskell #-} | |
module Main where | |
import Control.Monad | |
import Control.Monad.Free | |
import Control.Monad.Free.TH | |
data DslCmd next = | |
GetValue' | |
Int | |
(Int -> next) | |
deriving (Functor) | |
makeFree ''DslCmd | |
type DslCmdM = Free DslCmd | |
myProgram :: DslCmdM [Int] | |
myProgram = loop [0..1000000] | |
where loop = mapM getValue' | |
runCmd :: DslCmd (IO a) -> IO a | |
runCmd (GetValue' v n) = n (2 * v) | |
main :: IO () | |
main = do | |
r <- iterM runCmd myProgram | |
print $ sum r | |
return () |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment