haskell - Understanding how Either is an instance of Functor -
in free time i'm learning haskell, beginner question.
in readings came across example illustrating how either a made instance of functor:
instance functor (either a) fmap f (right x) = right (f x) fmap f (left x) = left x now, i'm trying understand why implementation maps in case of right value constructor, doesn't in case of left?
here understanding:
first let me rewrite above instance as
instance functor (either a) fmap g (right x) = right (g x) fmap g (left x) = left x now:
i know
fmap :: (c -> d) -> f c -> f dif substitute
feither afmap :: (c -> d) -> either c -> either dthe type of
right (g x)either (g x), , type ofg xd, have type ofright (g x)either d, expectfmap(see 2. above)now, if @
left (g x)can use same reasoning typeeither (g x) b,either d b, not expectfmap(see 2. above):dshould second parameter, not first! can't map onleft.
is reasoning correct?
this right. there quite important reason behavior: can think of either b computation, may succeed , return b or fail error message a. (this also, how monad instance works). it's natural, functor instance won't touch left values, since want map on computation, if fails, there's nothing manipulate.
Comments
Post a Comment