groupBy没有按照我的预期行事,我在寻找什么?

Vik*_*ren 3 grouping haskell

isPermutation :: (Ord a) => [a] -> [a] -> Bool
isPermutation x y = sort x == sort y

isPermutation "123" "312" -> True
isPermutation "123" "111" -> False

groupBy isPermutation ["123","3","321"] -> ["123","3","321"] <- What I get

groupBy isPermutation ["123","3","321"] -> [["123","321"],"3"] <- What I would want
Run Code Online (Sandbox Code Playgroud)

是否有一个功能将列表中共享相同属性的项目组合在一起?

sha*_*ang 6

groupBy仅对具有相同属性的连续元素进行分组,例如

> groupBy (==) [1,2,1,1,2]
[[1],[2],[1,1],[2]]
Run Code Online (Sandbox Code Playgroud)

要对所有元素进行分组,首先需要对列表进行排序.

> groupBy isPermutation . sortBy (comparing sort) $ ["123","3","321"]
[["123","321"],["3"]]
Run Code Online (Sandbox Code Playgroud)

(comparing从中导入Data.Ord)