Skip to content

Instantly share code, notes, and snippets.

@adbrowne
Created February 11, 2016 01:35
Show Gist options
  • Save adbrowne/27342cd83a412e040647 to your computer and use it in GitHub Desktop.
Save adbrowne/27342cd83a412e040647 to your computer and use it in GitHub Desktop.
Church encoded free monads vs not
-- 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 ()
-- 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