I wrote this function:
appFunc :: Integer -> Integer -> Bool -> Maybe (Integer,Integer)
appFunc i1 i2 b = if b then Just (i1,i2) else Nothing
And then I use it as such in GHCi:
> appFunc <$> Just 3 <*> Nothing <*> Just True
Nothing
Which is great because if at least one of the parameters is Nothing
then the whole expression evaluates to Nothing
. However, when all parameters are Just
then I get a nested Maybe
:
> appFunc <$> Just 3 <*> Just 1 <*> Just False
Just Nothing
Ideally, I would like it to evaluate to plain old Nothing
. So my solution was to use join
:
> join $ appFunc <$> Just 3 <*> Just 1 <*> Just True
Just (3,1)
Is there a better solution or cleaner style? I was experimenting with the monad >>=
function but with no success. For example I tried writing:
> Just True >>= appFunc <$> Just 3 <*> Just 1
* Couldn't match expected type `Bool -> Maybe b'
with actual type `Maybe (Bool -> Maybe (Integer, Integer))'
* Possible cause: `(<*>)' is applied to too many arguments
In the second argument of `(>>=)', namely
`appFunc <$> Just 5 <*> Just 4'
In the expression: Just True >>= appFunc <$> Just 5 <*> Just 4
In an equation for `it':
it = Just True >>= appFunc <$> Just 5 <*> Just 4
* Relevant bindings include
it :: Maybe b (bound at <interactive>:51:1)
This error makes sense to me because:
appFunc <$> Just 3 <*> Just 1 :: m (a -> m b)
whereas >>= :: m a -> (a -> m b) -> m b
Is there a monad solution or should I just stick to the applicative style with join
?