Created
September 18, 2017 18:39
-
-
Save neocris/f3aecae7ff4a53490b140a0251629f3a to your computer and use it in GitHub Desktop.
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 Data.Monoid (Monoid, (<>)) | |
-- writer monad. is a way to put a monad structure on tuples | |
-- see https://wiki.haskell.org/Monoid#On_the_Writer_monad | |
{- | |
(w,x) >>= f = | |
case f x of | |
(v, y) -> (w <> v, y) | |
-} | |
-- the monoidal instance of tuple/product allows accumulating -<>- successive 'logs' -a<>c- for each computation -gx,fb | |
newtype Mem s a = | |
Mem { | |
runMem :: s -> (a,s) | |
} | |
instance Monoid a => Monoid (Mem s a) where | |
mempty = Mem $ \s -> (mempty, s) | |
mappend Mem {runMem = f} Mem {runMem = g} = Mem $ \x -> let (a, b) = g x | |
(c, d) = f b | |
in (a <> c, d) | |
f' = Mem $ \s -> ("hi", s + 1) | |
main = do | |
print $ runMem (f' <> mempty) 0 | |
print $ runMem (mempty <> f') 0 | |
print $ (runMem mempty 0 :: (String, Int)) | |
print $ runMem (f' <> mempty) 0 == runMem f' 0 | |
print $ runMem (mempty <> f') 0 == runMem f' 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment