gpt4 book ai didi

haskell - groupBy 没有达到我的预期,我在寻找什么?

转载 作者:行者123 更新时间:2023-12-02 16:26:25 26 4
gpt4 key购买 nike

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

是否有一个函数可以将列表中具有相同属性的项目分组在一起?

最佳答案

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

> groupBy (==) [1,2,1,1,2]
[[1],[2],[1,1],[2]]

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

> groupBy isPermutation . sortBy (comparing sort) $ ["123","3","321"]
[["123","321"],["3"]]

(比较是从Data.Ord导入的)

关于haskell - groupBy 没有达到我的预期,我在寻找什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21206345/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com