Why is the "guard" not defined using the MonadPlus restriction?

I am currently reading about Alternative / MonadPlus classes on wikibooks . He describes this difference very well. However, one cryptic part is the guard function, which I assume is used to "short circuit" the calculation. (Right?)

The guard function, although defined in Control.Monad , has an Alternative constraint, as described below ( link ).

 guard :: (Alternative f) => Bool -> f () guard True = pure () guard False = empty 

But in the above article it is mentioned that only MonadPlus is required to ensure the left zero and right zero level MonadPlus (Therefore, a stronger requirement).

 mzero >>= f = mzero -- left zero m >> mzero = mzero -- right zero 

Given the purpose of the guard function, shouldn't it be defined using the MonadPlus restriction? Don't we need stronger laws if guard should short-circuit the computation? I am interested to know the reason for a specific design choice.

ps: I don’t know what is the best way to describe the behavior "cancel precalculating" other than the word "short circuit"?

+5
source share
1 answer

guard has an Applicative constraint because you do not need to perform monadic operations on it to define a function.

This definition (copied from Source hacks ):

 guard :: (Alternative f) => Bool -> f () guard True = pure () guard False = empty 

If he indicated MonadPlus instead of Alternative , he would not get anything. MonadPlus is a subclass of Alternative , so all MonadPlus instances can use guard , but not all Alternatives can use it.

(Although there would be very few Alternatives exceptions - both cases mentioned here have an instance of MonadPlus , although they do not satisfy the left-distribution rule.)

In general, it is best to adhere to the minimum restrictions necessary to write a function, even if the intended use is more specific. Thus, there is nothing excluded, which should not be, and no complaints from people whose types can work for him, but are not monads.

By the way, Google Search results do not correctly display the MonadPlus restriction, but if you click the link, it will be correct.

0
source

Source: https://habr.com/ru/post/1263813/


All Articles