編譯器說:
Could not deduce (Ord a) arising from a use of ‘<=’
from the context (Eq a)
bound by the type signature for groupElems :: Eq a => [a] -> [[a]]
什麼Haskell編譯旨在要說的是,你用<= x
OM你的代碼,但<=
功能是Eq
的不部分typeclass:如果我們問<=
來自哪裏,我們得到:
Prelude> :i (<=)
class Eq a => Ord a where
...
(<=) :: a -> a -> Bool
...
-- Defined in ‘GHC.Classes’
infix 4 <=
所以我們可以通過使用Ord
typeclass解決問題:這意味着元素是有序的。但根據你的例子,這是而不是你想要什麼。如果我們用Ord a
類型的約束,如:
groupElems :: Ord a => [a] -> [[a]]
groupElems [] = []
groupElems (x:xs) =
let (a,b) = span (<= x) xs
in a : (groupElems b)
的第二個問題是,我們*調用span
的xs
名單上。 xs
是尾部的名單。所以這意味着我們不會考慮頭腦。我們可以通過使用別名@
改變這種和處理整個列表xa
:
groupElems :: Ord a => [a] -> [[a]]
groupElems [] = []
groupElems [email protected](x:_) =
let (a,b) = span (<= x) xa
in a : (groupElems b)
我們將獲得:
GHci > groupElems []
[]
GHci > groupElems [1,2]
[[1],[2]]
GHci > groupElems [1,2,2,2,4]
[[1],[2,2,2],[4]]
GHci > groupElems [1,2,3,2,4]
[[1],[2],[3,2],[4]]
注意最後一個測試用例是不正確的。這是因爲3
和2
都滿足<= 3
謂詞。
如果你想按平等,你應該使用(==) :: Eq a => a -> a -> Bool
功能:
groupElems :: Eq a => [a] -> [[a]]
groupElems [] = []
groupElems [email protected](x:_) =
let (a,b) = span (== x) xa -- use == instead of <=
in a : (groupElems b)
然後產生:
GHci > groupElems []
[]
GHci > groupElems [1,2]
[[1],[2]]
GHci > groupElems [1,2,2,2,4]
[[1],[2,2,2],[4]]
GHci > groupElems [1,2,3,2,4]
[[1],[2],[3],[2],[4]]
請張貼您獲得錯誤。此外,不要簡單地停止「有編譯器錯誤」,而是顯示你認爲錯誤的含義是很好的。通常,編譯器旨在描述錯誤是什麼。 –