这有什么问题? 我试着写一个定义如下的排序函数:
let orderFunction:: Num b => (a, [b]) -> (a, [b]) -> Ordering;
orderFunction a1 a2 = if sum $ snd a1 > sum $ snd a2 then GT else LT
但是我收到了错误:
Could not deduce (Ord b) arising from a use of `>'
from the context (Num b)
bound by the type signature for
orderFunction :: Num b => (a, [b]) -> (a, [b]) -> Ordering
at <interactive>:110:21-61
Possible fix:
add (Ord b) to the context of
the type signature for
orderFunction :: Num b => (a, [b]) -> (a, [b]) -> Ordering
In the expression: sum (snd a1) > sum (snd a2)
In the expression: if sum (snd a1) > sum (snd a2) then GT else LT
In an equation for `orderFunction':
orderFunction a1 a2
= if sum (snd a1) > sum (snd a2) then GT else LT
是否有更多面向Haskell的方法来编写函数?
谢谢, FB
答案 0 :(得分:3)
正如@ymonad所指出的,Num类型类并不意味着支持订购功能。所以我在函数定义中添加了另一个约束,如下所示:
let orderFunction::(Ord b, Num b) => (a, [b]) -> (a, [b]) -> Ordering;
orderFunction a1 a2 = if sum (snd a1) > sum (snd a2) then GT else LT