当我尝试您的代码时,我收到以下错误消息(诚然有些冗长且令人困惑):
EveryOther.hs:4:42: error:
• Couldn't match type ‘b’ with ‘a’
‘b’ is a rigid type variable bound by
the type signature for:
applyToEveryOther :: forall a b. (a -> b) -> [a] -> [b]
at EveryOther.hs:1:22
‘a’ is a rigid type variable bound by
the type signature for:
applyToEveryOther :: forall a b. (a -> b) -> [a] -> [b]
at EveryOther.hs:1:22
Expected type: [a]
Actual type: [b]
• In the second argument of ‘(:)’, namely ‘applyToEveryOther f xs’
In the second argument of ‘(:)’, namely
‘y : applyToEveryOther f xs’
In the expression: f x : y : applyToEveryOther f xs
• Relevant bindings include
xs :: [a] (bound at EveryOther.hs:4:26)
y :: a (bound at EveryOther.hs:4:24)
x :: a (bound at EveryOther.hs:4:22)
f :: a -> b (bound at EveryOther.hs:4:19)
applyToEveryOther :: (a -> b) -> [a] -> [b]
(bound at EveryOther.hs:2:1)
但是,值得尝试弄清楚 GHC 在这里所说的内容。根据第二个要点,GHC 正在处理子表达式y : applyToEveryOther f xs,并专门查看该表达式中: 运算符的第二个参数(即applyToEveryOther f xs。它预计该表达式的类型为[a],但是表达式的实际类型是[b]。
这里,a 和 b 都是“刚性”类型,这意味着它们是由程序员明确指定的。 GHC 还指出,在相关绑定中,y 的类型为 a。
所以,总而言之,您要求 GHC 评估表达式:
y : applyToEveryOther f xs
您已经指定 y 的类型为 a 和 applyToEveryOther f xs 的类型为 [b],而 GHC 拒绝这样做,因为 Haskell 中的列表不能混合两种不同的类型。
这就是整个问题的关键所在。您想将[a] 列表中的一些元素从a 转换为b,但是您想返回as 和bs 的混合列表。 Haskell 做不到!
您的函数可以工作的唯一方法是更改签名以使a 和b 是同一类型:
applyToEveryOther :: (a -> a) -> [a] -> [a]
您的代码将正常工作。
另一种“发现”正确签名的方法是将其排除在外,让 Haskell 推断出最普遍的可能签名。如果您将代码(没有显式签名)加载到 GHCi 并询问类型,您会得到:
> :t applyToEveryOther
applyToEveryOther :: (a -> a) -> [a] -> [a]
>
这是此函数最通用的可能类型。