From 53373f5fa74a8154ea9d13ba633ffd57ea2d1b75 Mon Sep 17 00:00:00 2001 From: Anastasios Valtinos Date: Thu, 3 Nov 2022 12:05:27 +0200 Subject: [PATCH] Functor, Applkicative, Monad instance for MaybeT transformer --- .../Alejandro - Book of Monads/MonadicCode.hs | 22 ++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/Haskell Excercises & Code/Alejandro - Book of Monads/MonadicCode.hs b/Haskell Excercises & Code/Alejandro - Book of Monads/MonadicCode.hs index 8ffbf82..1a426b7 100644 --- a/Haskell Excercises & Code/Alejandro - Book of Monads/MonadicCode.hs +++ b/Haskell Excercises & Code/Alejandro - Book of Monads/MonadicCode.hs @@ -95,4 +95,24 @@ instance Applicative (EitherX e) where instance Monad (EitherX e) where return = RightX RightX m >>= k = k m - LeftX e >>= _ = LeftX e \ No newline at end of file + LeftX e >>= _ = LeftX e + + +newtype MaybeTX m a = MaybeTX { runMaybeTX :: m (Maybe a)} + +instance Functor m => Functor (MaybeTX m) where + fmap f (MaybeTX ma) = MaybeTX $ (fmap . fmap) f ma + +instance Applicative m => Applicative (MaybeTX m) where + pure x = MaybeTX (pure (pure x)) + MaybeTX rfa <*> MaybeTX rxa = MaybeTX $ (<*>) <$> rfa <*> rxa + +instance Monad m => Monad (MaybeTX m) where + return x = MaybeTX $ return (Just x) + MaybeTX ma >>= f = MaybeTX $ do + maybeValue <- ma + case maybeValue of + Nothing -> return Nothing + Just y -> runMaybeTX (f y) + +