I wrote something like this:
instance Functor (Either e) where
fmap _ (Left a) = Left a
fmap f (Right b) = Right (f b)
How do I do the same if I want fmap to change the value only if it’s Left?
I mean, what syntax do I use to indicate that I use type Either _ b instead of Either a _?
I don’t think there’s a way to do that directly, unfortunately. With a function you can use
flipto partially apply the second argument, but that doesn’t work with type constructors likeEither.The simplest thing is probably wrapping it in a
newtype:Wrapping with
newtypeis also the standard way to create multiple instances for a single type, such asSumandProductbeing instances ofMonoidfor numeric types. Otherwise, you can only have one instance per type.Additionally, depending on what it is you want to do, another option is to ignore
Functorand define your own type class like this:Obviously, that class is twice as much fun as a regular
Functor. Of course, you can’t make aMonadinstance out of that very easily.