我必须重载函数排序。函数的参数是一个数字,它们必须按参数
0
的值排序。这是我的尝试:Haskell函数重载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)'
我也想实例化奥德类名单。列表排序将通过每个列表的第一个元素之间的比较给出。例如[1,2] < [2,3]因为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没有函数重载。 – pdexter
因为那么'[1,1] <= [1,2]'和'[1,2] <= [1,1]'但当然是'[1,1]/= [1,2]' - 你也无法比较空列表...你为什么要这样做? – Carsten
这个练习的目的是理解不做“有意义”的事情的原则。 – zaig