为什么在工作函数中添加as-pattern会导致编译错误?

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,即它必须允许ab不同.在您的实现中,a并且b只能是相同的,因为它返回作为参数传递的相同内容.所以GHC抱怨道.

  • @MattFenwick微妙的是左边的"左"和右边的"左"不是一回事; 右边的那个更具多态性!您可能想尝试编写`data Phantom a = Phantom`并比较`fa @ Phantom = a`和`g Phantom = Phantom`的类型. (9认同)