Search code examples
functionhaskellpattern-matchingfunctor

Functor fmap, pattern match function values, haskell


I have the following type, and would like to make it a Functor:

newtype SubsM a = SubsM {runSubsM :: Context -> Either Error (a, Env)}

So far i got this

instance Functor SubsM where
    fmap f (SubsM a)  =  SubsM (\s->(Right((f a),(fst s))))

I get an error because a is not the expected type, my question is how do i pattern match a on the left-hand side?


Solution

  • You can pattern match on the Either Error (a, Env) with case:

    instance Functor SubsM where
      fmap f (SubsM cf) = SubsM $ \c ->  case (cf c) of
        Left err -> Left err
        Right (v, env) -> Right (f v, env)
    

    In the Left case you propagate the error, in the Right case you unpack the resulting pair and apply f to the first element.