At Haskell, working with Maybe and Either slightly weaker than Scala, so maybe you can rethink this approach. If you do not mind, I will use your first example to show this.
First, you usually do not check for null. Instead, you would simply calculate the property you are interested in using Maybe to handle the failure. For example, if what you really wanted was the head of the list, you could simply write this function:
For something that is purely hasText , like hasText , you can use a guard that works for any MonadPlus like Maybe :
guard :: (MonadPlus m) => Bool -> m () guard precondition = if precondition then return () else mzero
When you specialize guard in the Maybe monad, then return becomes Just and mzero becomes Nothing :
guard precondition = if precondition then Just () else Nothing
Now suppose we have the following types:
foo :: [A] bar :: SomeForm hasText :: SomeForm -> Bool magic :: A -> SomeForm -> B
We can handle errors for both foo and bar and safely retrieve values for the magic function using the do notation for Maybe monad:
example :: Maybe B example = do a <- headMay foo guard (hasText bar) return (magic a bar)
If you are familiar with the notation of Scala, do , like Scala for understanding. The above code contains the following parameters:
example = headMay foo >>= \a -> guard (hasText bar) >>= \_ -> return (magic a bar)
In the monad Maybe (>>=) and return have the following definitions:
m >>= f = case m of Nothing -> Nothing Just a -> fa return = Just
... therefore the above code is just concise for:
example = case (headMay foo) of Nothing -> Nothing Just a -> case (if (hasText bar) then Just () else Nothing) of Nothing -> Nothing Just () -> Just (magic a bar)
... and you can simplify this:
example = case (headMay foo) of Nothing -> Nothing Just a -> if (hasText bar) then Just (magic a bar) else Nothing
... this is something you could write manually without do or guard .