当制作我的自定义Either
和Functor
,只是为了了解更清晰的类型和类型类,我发现了以下情况:为什么我无法在Haskell中使用id的Functor实例?
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
的上面显示的代码编译得很好但是,如果我改变它使用id
,它不会编译:
instance Functor (Either a) where
fmap f (Right x) = Right (f x)
fmap _ = id
为什么?我错过了什么?下面的代码也不起作用:
instance Functor (Either a) where
fmap f (Right x) = Right (f x)
fmap f [email protected](Left x) = all
...这似乎对我很奇怪,因为该代码显示如下编译:
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 [email protected](Rectangle _ x) = show all ++ " - "++ show x
预先感谢您
带有'id'的第一种情况在[这个问题]中有很好的解释(http://stackoverflow.com/questions/8745597/defining-a-function-by-equations-with-different-number-of-参数)。顺便说一下,一定要注意并提到你的问题,你会得到具体的错误 - 这使得你和答复者都能够更轻松地找到答案。 – duplode
伟大的一点,我会保持它 – FtheBuilder
如果你有兴趣在免费的表达,你可能会认为这个定义很可爱:'fmap =任何id' – dfeuer