我用Data.List.groupBy
寫了一些東西。它沒有按預期工作,所以我最終寫了我自己的版本groupBy
:畢竟我不確定Data.List
應該這樣做(沒有真正的文檔)。什麼是羣體應該做的?
無論如何,我的測試通過了我的版本groupBy
,而它的失敗與Data.List
。 我發現(感謝quickcheck
)兩個函數行爲不同的情況,我仍然不明白爲什麼這兩個版本之間存在差異。是Data.List
版本的車或是我的? (當然,我的天真實施並不是最有效的方式)。
下面是代碼:在GHC運行
import qualified Data.List as DL
import Data.Function (on)
import Test.QuickCheck
groupBy' :: (a -> a -> Bool) -> [a] -> [[a]]
groupBy' _ [] = []
groupBy' eq (x:xs) = xLike:(groupBy' eq xNotLike) where
xLike = x:[ e | e <- xs, x `eq` e ]
xNotLike = [ e | e <- xs, not $ x `eq` e ]
head' [] = Nothing
head' (x:xs) = Just x
prop_a s = (groupBy' by s) == (DL.groupBy by s) where
types = s :: [String]
by = (==) `on` head'
quickCheck prop_a
回報["", "a", ""]
*Main> groupBy' ((==) `on` head') ["","a",""]
[["",""],["a"]] # correct in my opinion
*Main> DL.groupBy ((==) `on` head') ["","a",""]
[[""],["a"],[""]] # incorrect.
發生了什麼事?我無法相信haskell平臺有bug。
'groupBy'函數將一個列表分割成幾部分,例如'concat。 groupBy f == id'(以及其他法律)。 – augustss