I am currently reading about the Alternative/MonadPlus typeclasses in wikibooks. It describes the difference very well. However, one puzzling part is the guard function, which I am assuming, is used for "short-circuiting" a computation. (Am I right?)
The function guard although defined in Control.Monad has an Alternative constraint, as following (link).
guard :: (Alternative f) => Bool -> f ()
guard True = pure ()
guard False = empty
But the above article, mentions that only the MonadPlus is required to enforce the left zero and right zero laws (Hence the stronger claim).
mzero >>= f = mzero -- left zero
m >> mzero = mzero -- right zero
Given the purpose of the guard function, shouldn't it be defined with a MonadPlus constraint? Don't we need the stronger laws if guard is supposed to "short-circuit" the computation? I am curious about the reason behind the specific design choice.
p.s.: I don't know what is a better way to describe the "cancelling the upfront computation" behavior other than the word "short-circuiting"?
MonadPlusis stronger thanAlternativeand you don't needMonadPlusto writeguard- the type withAlternativeis the most general type, i.e. the inferred one. Why would one give it a stronger type? (Note the wikibooks page is outdated post-AMP, so ghc 8 and up? I don't actually remember..) - user2407038Applicativecontext:guard False *> x = emptyandguard True *> x = x; it simply also works forMonadin the same natural way as all things which work forApplicativewill work forMonad. - user2407038Alternativedoesn't mandate theempty *> x == emptylaw. So it might not be true for all instances. Am I right? - zerononeguardwasMonadPlus m => ..., but everyMonadPlusis now anAlternative, and by defaultmzero = emptyandmplus = (<|>). Therefore, if you have a type that's both aMonadand anAlternative, it should hold those laws. However, that should be stated in either theclass Alternativeor theclass Monaddocumentation. That being said, the functionality ofguardwasn't reduced.mzeroisemptyon all commonMonadPlusinstances. - Zeta