Let us say, I have two Maybe Bool value and I want to achieve the following functionality:
Just values, I want to perform an || between them the values.Nothing and the other one is Just value, then I want the Just value as the output.Nothing, then I want Just False as the output.I know that this can be achieved using pattern matching. But is it possible to use any monadic functions to acheive the result ?
liftM2 works for this case:
ghci> liftM2 (||) (Just True) (Just False)
Just True
But liftM2 will produce Nothing when any of the one input is Nothing (for which I want the other Just value). i.e:
ghci> liftM2 (||) (Nothing) (Just False)
Nothing
But I want Just False in the above case.
Is it possible to do this using any monadic function ?
As it stands, we don't even need to invoke the monadic apparatus. According to your specification, "Nothing" can be mapped to "False" and "Just b" to "b":
mbor a b = Just (flat a || flat b)
where flat = maybe False id
As @leftaroundabout correctly points out this essentially is what the Monoid Any instance does.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With