Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nothing in MaybeT monad: more concise way?

Tags:

haskell

monads

I'm experimenting with the MaybeT monad, specifically MaybeT Identity String

import Control.Monad.Trans.Maybe
import Control.Monad.Identity
import Data.Maybe

main :: IO ()
main = putStrLn . show . runIdentity . runMaybeT $ maybeGetString

maybeGetString :: MaybeT Identity String
maybeGetString = return "first" >>
                 maybeTNothing >> 
                 return "second"

maybeTNothing :: MaybeT Identity String
maybeTNothing = MaybeT $ return Nothing

The experession for the MaybeT equivalent of Nothing seems to be MaybeT $ return Nothing, which feels a bit verbose, and it feels unexpected to me to have to explicitly use the MaybeT constructor.

Is there a shorter/nicer/clearer way of writing Nothing in the MaybeT monad?

like image 912
Michal Charemza Avatar asked Oct 17 '22 13:10

Michal Charemza


1 Answers

Inspired by the comment from @luqui


To behave as Nothing in the plain Maybe monad, maybeTNothing should satisfy the equations

maybeTNothing >>= f  =  maybeTNothing
v >> maybeTNothing   =  maybeTNothing

This is exactly the requirements on mzero from MonadPlus, which MaybeT is an instance of. So we can just use mzero

maybeTNothing = mzero

https://hackage.haskell.org/package/base-4.9.1.0/docs/Control-Monad.html#t:MonadPlus

like image 90
Michal Charemza Avatar answered Nov 15 '22 06:11

Michal Charemza