Functor typeclass
fmap :: (a -> b) -> f a -> f b
其中的f a,f为类型构造子,a为值构造子,f后不能接[a],因为[a]已经是一个具体的类型,其中[ ]也是一个类型构造子。
所以针对Maybe的instance,写法为:
instance Functor Maybe where
fmap f (Just x) = Just (f x)
fmap f Nothing = Nothing
注意是
instance Functor Maybe where
,而不是instance Functor (Maybe m) where,
因为Functor
要的是一个接受一个类型参数的类型构造子而不是一个具体类型。
不同的是
instance YesNo (Maybe a) where
,这里的Yesno接收的是一个具体的类型而不是一个类型构造子。
另一个不同的是
instance Functor (Either a) where
,Functor后面跟的是Either a ,因为Either a作为一个整体才是一个接收一个
类型参数的类型构造子,而Either是一个接收两个类型参数的类型构造子。
instance Functor (Either a) where
fmap f (Right x) = Right (f x)
fmap f (Left x) = Left x
如何运用上面这部分内容?