Either 型に関数を適用する。

Real World Haskell 10.5.3 「柔軟なインスタンス」に Either 型に関数を適用する例がありました。
Haskell 98では出来なくて、GHC で {-# LANGUAGE FlexibleInstances #-} を指定する必要があります。

{-# LANGUAGE FlexibleInstances #-}

instance Functor (Either Int) where
    fmap _ (Left n)  = Left n
    fmap f (Right r) = Right (f r)
>  fmap (++",world!") (Left 256::Either Int String)      --=> Left 256
>  fmap (++",world!") (Right "Hello"::Either Int String) --=> Right "Hello,world!"
>  (++",world!")  `fmap` (Right "Hello"::Either Int String) --=> Right "Hello,world!"
  • ファンクタは id を適用した結果は元のものと同一でなければならない。
> fmap id (Left 256::Either Int String)  --=> Left 256

>  :t fmap id (Left 256::Either Int String)   
 --=> fmap id (Left 256::Either Int String) :: Either Int String

>  fmap id  (Right "Hello"::Either Int String) --=> Right "Hello"
  • ファンクタは合成可能でなければならない。
> fmap length (Right "Hello"::Either Int String)  --=> Right 5

> :t fmap length (Right "Hello"::Either Int String) 
--=> fmap length (Right "Hello"::Either Int String) :: Either Int Int

> (fmap even . fmap length) (Right "Hello"::Either Int String) 
 --=> Right False

> fmap (even .length) (Right "Hello"::Either Int String) --=> Right False
> fmap (even .length) (Left 256::Either Int String)  --=> Left 256