Search code examples
haskellfunctor

Mapping a functor to another in Haskell


I have a function that produces a Maybe a type and I'm using it in a function to produce an Either b a. Is there a way I can map Nothing to Left x to simplify my code? The following code gives some context:

rmX :: ... -> Maybe a
cvX :: ... -> Either CVXError a
data CVXError = BadIndex | NoCover | NoSpace
cvX ... =
  ...
  case rmx 1 xs of
    Nothing -> Left NoSpace
    Just p  -> Right (x2:x1:(fromJust (rmX (-1) p)))
-- given that rmX always passes on negative value arg

The case statement is just begging to be replaced with fmap but the problem is that I'm not sure how to 'map' Nothing to Left NoSpace in an fmap call or to even extract this pattern to make my own util function.


Solution

  • You're looking for the maybe function:

    cvX ... =
      ...
      maybe (Left NoSpace) (\p -> Right (x2:x1:(fromJust (rmX (-1) p)))) $
        rmX 1 xs