【发布时间】:2016-06-10 09:54:56
【问题描述】:
-
我必须重载函数排序。函数的参数是一个数字,它们必须按参数
0的值排序。这是我尝试过的:Prelude>instance (Num a, Ord b) => Ord (a -> b) where f > g = f 0 > g 0但它会产生错误
Could not deduce (Eq (a -> b)) arising from the superclasses of an instance declaration from the context (Num a, Ord b) bound by the instance declaration at <interactive>:117:10-39 In the instance declaration for `Ord (a -> b)' -
我还想为列表实例化 Ord 类。列表排序将通过每个列表的第一个元素之间的比较来给出。例如 [1,2]
instance Ord a => Ord [a] where (h1:_) <= (h2:_) = h1 <= h2这也会产生下一个错误:
Ambiguous occurrence `<=' It could refer to either `Main.<=', defined at C:\Users\user-name\Desktop\test.hs:2:8 or `Prelude.<=', imported from `Prelude' at C:\Users\user-name\Desktop\test.hs:1:1 (and originally defined in `GHC.Classes')
我想我可能不太了解 Haskell 中的函数重载。也许有人可以解释我做错了什么。
【问题讨论】:
-
您定义自己的
<=吗? Prelude 已经带有<=,所以你应该选择你想要的(这就是第二条错误消息的意思)。第一个错误是说函数之间没有相等的内置定义。此外,Haskell 没有函数重载。 -
你对列表的排序会很奇怪,因为
[1,1] <= [1,2]和[1,2] <= [1,1]当然[1,1] /= [1,2]- 你也不能比较空列表......你为什么要这样做?跨度> -
练习的目的是理解不做“有道理”的事情的原则。
-
你的练习需要你解决三件事:定义一个函数
<=,它将(尝试)适用于所有类型的参数;定义Ord类型类的新类型实例(您的案例 1);并定义一个现有类型的实例(对于[a])(您的2),即使您之前没有定义函数<=,它也不起作用,因为Prelude中已经存在Ord a => Ord [a]的实例.
标签: haskell