我必須重載函數排序。函數的參數是一個數字,它們必須按參數
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