Mat*_*ick 7 haskell types as-pattern
这是标准的Functor实例Either a
:
instance Functor (Either a) where
fmap _ (Left x) = Left x
fmap f (Right y) = Right (f y)
Run Code Online (Sandbox Code Playgroud)
在加载到GHCi中时,添加as-pattern会导致编译错误:
instance Functor (Either a) where
fmap _ z@(Left x) = z -- <-- here's the as-pattern
fmap f (Right y) = Right (f y)
Couldn't match expected type `b' against inferred type `a1'
`b' is a rigid type variable bound by
the type signature for `fmap' at <no location info>
`a1' is a rigid type variable bound by
the type signature for `fmap' at <no location info>
Expected type: Either a b
Inferred type: Either a a1
In the expression: z
In the definition of `fmap': fmap _ (z@(Left x)) = z
Run Code Online (Sandbox Code Playgroud)
为什么这不起作用?
Cat*_*lus 11
fmap
有签名(a -> b) -> f a -> f b
,即它必须允许a
和b
不同.在您的实现中,a
并且b
只能是相同的,因为它返回作为参数传递的相同内容.所以GHC抱怨道.