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
是否有一个功能将列表中的项目组合在一起,共享相同的属性?
答案 0 :(得分:6)
groupBy
仅将连续的元素分组,这些元素共享相同的属性,例如。
> groupBy (==) [1,2,1,1,2]
[[1],[2],[1,1],[2]]
要对所有元素进行分组,首先对列表进行排序。
> groupBy isPermutation . sortBy (comparing sort) $ ["123","3","321"]
[["123","321"],["3"]]
(comparing
是从Data.Ord
)
答案 1 :(得分:1)
你想要的是一个多路分区。利用Data.Map.insertWith
:
Prelude Data.List Data.Map> Data.List.map (reverse.snd) $ toList $
foldl (\mp s-> insertWith (++) (sort s) [s] mp) empty ["123", "3", "321"]
[["123","321"],["3"]]
这样每个元素只被排序一次。
相反,使用decorate-sort-undecorate惯用法和排序解决方案。