繁体   English   中英

无法推导(Eq i)由文字'0'引起的

[英]Could not deduce (Eq i) arising from the literal ‘0’

我是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约束。 =)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM