gpt4 book ai didi

haskell - 无法从文字 ‘0’ 中推断出 (Eq i)

转载 作者:行者123 更新时间:2023-12-05 08:33:20 26 4
gpt4 key购买 nike

我是 Haskell 的新手,正在尝试编写一个类似于 take 的函数,即从指定列表中返回指定数量的项目。我的代码如下:

take' :: (Num i, Ord a) => i -> [a] -> [a]
take' 0 _ = []
take' _ [] = []
take' n (x:xs) = x : take' (n - 1) xs

但是,当我尝试编译它时,我收到以下错误:

Could not deduce (Eq i) arising from the literal ‘0’
from the context (Num i, Ord a)
bound by the type signature for
take' :: (Num i, Ord a) => i -> [a] -> [a]
at recursion.hs:1:10-42
Possible fix:
add (Eq i) to the context of
the type signature for take' :: (Num i, Ord a) => i -> [a] -> [a]
In the pattern: 0
In an equation for ‘take'’: take' 0 _ = []

我认为该错误是由于 Haskell 无法将 0 识别为类类型 Num 的成员而引起的,但我不确定。任何人都可以向我解释错误并告诉我如何解决它。

最佳答案

针对文字数字的模式匹配脱糖到相等性检查。所以

take' 0 _ = []

成为

take' x _ | x == 0 = []

(其中 x 被选为子句中其他任何地方未提及的变量)。所以要支持这个模式,你需要拿的东西的数量不仅仅是一个Num,还要支持(==)!这就是错误的这一部分所说的:

Could not deduce (Eq i) arising from the literal ‘0’
In the pattern: 0
In an equation for ‘take'’: take' 0 _ = []

您可以只采用 GHC 在错误中建议的修复:

Possible fix:
add (Eq i) to the context of
the type signature for take' :: (Num i, Ord a) => i -> [a] -> [a]

因此:

take' :: (Eq i, Num i, Ord a) => i -> [a] -> [a]

之后您可以考虑是否需要 Ord a 约束。 =)

关于haskell - 无法从文字 ‘0’ 中推断出 (Eq i),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42304653/

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