Haskell 无法从文字‘;0’;

Haskell 无法从文字‘;0’;,haskell,Haskell,我是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’

我是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]
因此:


之后,您可以考虑是否需要
Ord a
约束

你想要
take':(Num a,Eq a)=>a->[a]->[a]
@Alec:我想他想要
take':(Num a,Eq a)=>a->[b]->[b]
:)你需要为
I
添加
约束:
(Num I,Eq I,Ord a)=>I->[a]
虽然不清楚
Ord
a
的约束是为了什么。@WillemVanOnsem是的!谢谢你。@WillemVanOnsem它工作了!!!谢谢
take' :: (Eq i, Num i, Ord a) => i -> [a] -> [a]