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:

  1. i know fmap :: (c -> d) -> f c -> f d

  2. if substitute f either a fmap :: (c -> d) -> either c -> either d

  3. the type of right (g x) either (g x), , type of g x d, have type of right (g x) either d, expect fmap (see 2. above)

  4. now, if @ left (g x) can use same reasoning type either (g x) b, either d b, not expect fmap (see 2. above): d should second parameter, not first! can't map on left.

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

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -