Skip to content

Instantly share code, notes, and snippets.

@pete-murphy
Created May 12, 2018 00:26
Show Gist options
  • Save pete-murphy/26e165ccb70d4f8d704fea3dd772f896 to your computer and use it in GitHub Desktop.
Save pete-murphy/26e165ccb70d4f8d704fea3dd772f896 to your computer and use it in GitHub Desktop.
Ch 15.15 (Monoid Exercises)
module Mem where
import Data.Monoid hiding ((<>))
import Data.Semigroup
newtype Mem s a =
Mem {
runMem :: s -> (a,s)
}
instance Monoid a => Monoid (Mem s a) where
mempty = Mem $ \x -> (mempty, x)
mappend (Mem f) (Mem f') =
Mem $ \x ->
-- Taking the first values of the (a,s) tuples
-- returned from applying each function, I should
-- get two 'a's that I can mappend together?
( (fst $ f x) `mappend` (fst $ f' x)
-- Then I am taking the s (second of the (a,s) tuple)
-- returned from applying f', and applying that to f
, (snd $ f $ snd $ f' x)
)
f' = Mem $ \s -> ("hi", s + 1)
main :: IO ()
main = do
let rmzero = runMem mempty 0
rmleft = runMem (f' <> mempty) 0
rmright = runMem (mempty <> f') 0
print $ rmleft
print $ rmright
print $ (rmzero :: (String, Int))
print $ rmleft == runMem f' 0
print $ rmright == runMem f' 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment