开发者

Haskell -- what to use for a labelled set partition?

Beginner question -- what do you usually use as a multimap? I want a function that takes a labelling function and partitions elements by each label. For example,

f x | x `mod` 2 == 0 = EVEN
    | otherwise = ODD

the output of partition f lst where lst :: [Int] would be

EVEN --> [list of even numbers]
ODD --> [sublist of odd numbers]
开发者_如何学运维

Sorry for the bother, I could not find something similar on Hoogle. I think I can get there via Data.List.Key's group function, sort, and some mapping, but there must be a simpler way, no? This seems like a generally useful function.


When there are only two cases, you can map them to booleans and use Data.List.partition.

Prelude Data.List> partition odd [1, 23, 42, 7, 1337, 8]
([1,23,7,1337],[42,8])

In the general case, you can use a Data.Map with a list or set as the value type. You can build one easily using Data.Map.fromListWith.

Prelude Data.Map> let partition f xs = fromListWith (++) [(f x, [x]) | x <- xs]
Prelude Data.Map> partition (`mod` 3) [1, 23, 42, 7, 1337, 8]
fromList [(0,[42]),(1,[7,1]),(2,[8,1337,23])]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜