gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:01:21 25 4
gpt4 key购买 nike

Here's Either a 的标准 Functor 实例:

instance Functor (Either a) where
fmap _ (Left x) = Left x
fmap f (Right y) = Right (f y)

在加载到 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

为什么这不起作用?

最佳答案

fmap有签名(a -> b) -> f a -> f b ,即它必须允许 ab与众不同。在您的实现中,ab只能是相同的,因为它返回作为参数传递的相同内容。所以GHC提示。

关于haskell - 为什么向工作函数添加 as-pattern 会导致编译错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12056257/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com