From 98329e0a3dd4f78b5d815ac3896272ec70904901 Mon Sep 17 00:00:00 2001 From: Eugen Wissner Date: Thu, 11 Dec 2025 10:28:11 +0100 Subject: Add remaining haskell book exercises --- Haskell-book/23/Moi.hs | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Haskell-book/23/Moi.hs (limited to 'Haskell-book/23/Moi.hs') 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) -- cgit v1.2.3