我有以下类型定义:
data NumList n = NumList [Rational]
然后在我的代码中我定义了一些像这样的数字列表,
n1 = NumList [1, 2, 3]
n2 = NumList [4, 5, 6]
我想做的是:
n3 = n1 + n2 -- Should be [5, 7, 9]
我尝试将其定义为:
toList :: NumList n -> [Rational]
toList (NumList n) = n
(+) :: NumList -> NumList -> NumList
(+) x y = if length x == length y
then
zipWith (+) toList x toList y -- This probably isn't right, but I'll debug this later
else
error "NumLists must be same length to add"
我得到的错误是:
Ambiguous occurrence `+'
It could refer to either `NumList.+',
defined at NumList.hs:7:5
or `Prelude.+'
我看不出这是多么模棱两可,因为 Prelude.+ 适用于Num
类,而 NumList.+ 仅适用于 NumList 类型。对此有何指导?还有一个小问题:有没有办法使用模式匹配从 (+) 函数中删除 if 表达式?