When making my custom Either
, and Functor
, just to understand clearer types and typeclasses, I found the following situation:
Functor
module Functor (Functor, fmap) where
import Prelude hiding(Functor, fmap)
class Functor f where
fmap :: (a -> b) -> f a -> f b
Either
module Either(Either(..)) where
import Prelude hiding(Either(..), Functor, fmap)
data Either a b = Left a | Right b deriving(Show)
instance Functor (Either a) where
fmap f (Right x) = Right (f x)
fmap _ (Left x) = Left x
The code showed above compiles fine but, if I change it to use id
, it doesn't compile:
instance Functor (Either a) where
fmap f (Right x) = Right (f x)
fmap _ = id
Why?? Did I miss something? The following code also doesn't work:
instance Functor (Either a) where
fmap f (Right x) = Right (f x)
fmap f all@(Left x) = all
... This seems to me very strange because the code showed below compiles:
data Shape = Circle Point Float | Rectangle Point Point deriving (Show)
data Point = Point Float Float deriving (Show)
test :: Shape -> String
test (Circle _ x) = show x
test all@(Rectangle _ x) = show all ++ " - "++ show x
Thank you in advance