分组重复

时间:2011-10-07 00:02:01

标签: haskell grouping

哈斯克尔大师。注意向我展示一些执行此任务的haskellian方法,这些方法不受我对haskell和FP的有限知识的限制吗?

groupDups [] = []
groupDups list@(x:xs) = groupDups' x list
  where groupDups' _ [] = []
        groupDups' x list = let (m,r) = partition (x ==) list
                            in m : groupDups r

> groupDups [1,2,3,4,1,2,3,4,4,3,2,1,4,3,2,1]
[[1,1,1,1],[2,2,2,2],[3,3,3,3],[4,4,4,4]]

4 个答案:

答案 0 :(得分:4)

您可以sort列表,然后group

> import Data.List
> (group . sort) [1,2,3,4,1,2,3,4,4,3,2,1,4,3,2,1]
[[1,1,1,1],[2,2,2,2],[3,3,3,3],[4,4,4,4]]

答案 1 :(得分:1)

如果您想避免在类型中引入Ord约束,可以使用:

import Data.List

groupDups []     = []
groupDups (x:xs) = (x : group) : groupDups xs' where
  (group,xs') = partition (==x) xs

它相应地比(group . sort)慢,并且组在原始列表中首次出现排序:

*Main> groupDups [1,3,2,3,4,1,2,3,4,4,3,2,1,4,3,2,1]
[[1,1,1,1],[3,3,3,3,3],[2,2,2,2],[4,4,4,4]]

您可以通过将辅助函数累积到参数列表中来稍微提高复杂性,询问​​您是否对细节感兴趣。

答案 2 :(得分:0)

这样做很奇怪。

groupDups ls = 
   map (\(h:­t) -> t) $ foldl­ (\s e -> map (\(h:­t) -> if h == e then (e:h:­t) else (h:t)­) s)   (nub [[x] | x <- ls])­ ls

答案 3 :(得分:0)

此功能仅需Eq

groupDups xs = foldl insert [] xs
  where insert [] x = [[x]]
        insert (ys@(y:_):yss) x | x == y    = (x:ys):yss
                                | otherwise = ys:(insert yss x)
相关问题