當製作我的自定義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