diff options
Diffstat (limited to 'Haskell-book/23/Moi.hs')
| -rw-r--r-- | Haskell-book/23/Moi.hs | 34 |
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) |
