aboutsummaryrefslogtreecommitdiff
path: root/Haskell-book/23/Moi.hs
diff options
context:
space:
mode:
authorEugen Wissner <belka@caraus.de>2025-12-11 10:28:11 +0100
committerEugen Wissner <belka@caraus.de>2025-12-11 10:28:11 +0100
commit98329e0a3dd4f78b5d815ac3896272ec70904901 (patch)
tree80f9c56cfe2ac20232358f236d32e84bd683be1b /Haskell-book/23/Moi.hs
parent3624c712d72d246f21d4e710cec7c11e052e0326 (diff)
downloadbook-exercises-98329e0a3dd4f78b5d815ac3896272ec70904901.tar.gz
Add remaining haskell book exercises
Diffstat (limited to 'Haskell-book/23/Moi.hs')
-rw-r--r--Haskell-book/23/Moi.hs34
1 files changed, 34 insertions, 0 deletions
diff --git a/Haskell-book/23/Moi.hs b/Haskell-book/23/Moi.hs
new file mode 100644
index 0000000..70352f3
--- /dev/null
+++ b/Haskell-book/23/Moi.hs
@@ -0,0 +1,34 @@
+module Moi where
+
+newtype Moi s a = Moi { runMoi :: s -> (a, s) }
+
+instance Functor (Moi s) where
+ -- fmap :: (a -> b) -> Moi s a -> Moi s b
+ fmap f (Moi g) = Moi (\x -> h $ g x)
+ where h (a, b) = (f a, b)
+
+instance Applicative (Moi s) where
+ -- pure :: a -> Moi s a
+ pure a = Moi (\s -> (a, s))
+ -- (<*>) :: Moi s (a -> b) -> Moi s a -> Moi s b
+ (Moi f) <*> (Moi g) = Moi (\s -> ((fst (f s)) (fst (g s)), s))
+
+instance Monad (Moi s) where
+ return = pure
+ -- (>>=) :: Moi s a -> (a -> Moi s b) -> Moi s b
+ (Moi f) >>= g = Moi (\s -> (runMoi (g (fst (f s)))) (snd (f s)))
+
+get :: Moi s s
+get = Moi $ \a -> (a, a)
+
+put :: s -> Moi s ()
+put s = Moi $ \_ -> ((), s)
+
+exec :: Moi s a -> s -> s
+exec (Moi sa) s = snd (sa s)
+
+eval :: Moi s a -> s -> a
+eval (Moi sa) s = fst (sa s)
+
+modify :: (s -> s) -> Moi s ()
+modify f = Moi $ \a -> ((), f a)