Handling Maybe Bool Values

Let's say I have two values Maybe Bool, and I want to achieve the following functions:

  • If both values Just, I want to execute ||between them values.
  • If one of them Nothingand the other is Just, then I want the value to be output Just.
  • If both of them Nothing, then I want Just Falseas a conclusion.

I know that this can be achieved through pattern matching. But is it possible to use any monadic functions to achieve the result?

liftM2 works for this case:

ghci> liftM2 (||) (Just True) (Just False)
Just True

But it liftM2will produce Nothingif any of one input Nothing(for which I want a different value Just). i.e:

ghci> liftM2 (||) (Nothing) (Just False)
Nothing

Just False .

?

+4
3

. 1 Nothing .

; Nothing , , Nothing, .

instance (Monoid a) => Monoid (Maybe a)

, Bool . , ! , - . newtype Data.Monoid:

newtype Any = Any { getAny :: Bool }
instance Monoid Any

...

Prelude Data.Monoid > fmap getAny $(Just $Any True) < > (Just $Any False)

Prelude Data.Monoid > fmap getAny $(Nothing) < > (Just $Any False)
False


1 , fail... .

+6

. "Nothing" "False" "Just b" "b":

mbor a b = Just (flat a || flat b)
   where flat = maybe False id

@leftaroundabout , , Monoid Any instance.

+9

<|> Alternative Control.Applicative. Maybe :

Just a  <|> _       = Just a
Nothing <|> Just a  = Just a
Nothing <|> Nothing = Nothing

, x || x == x . :

orMaybe a b = liftA2 (||) (a <|> b) (b <|> a) <|> Just False

a b Just x, liftA2 (||) Just (a || b). Nothing, (a <|> b) (b <|> a) a, b, Just (a || a) Just (b || b). , Nothing, liftA2 (||) Nothing Nothing, Nothing. <|> Just False Just False.

, , . ? ! Maybe Nothing ; , .

Note: liftA2comes from Control.Applicative. It's just like liftMthat, but for applications; I used it to match with <|>. You could use fmap.

+6
source

All Articles