4

初学者问题——你通常使用什么作为多图?我想要一个函数,它采用标签函数并按每个标签划分元素。例如,

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

partition f lstwhere的输出lst :: [Int]将是

EVEN --> [list of even numbers]
ODD --> [sublist of odd numbers]

抱歉打扰了,我在 Hoogle 上找不到类似的东西。我想我可以通过Data.List.Keygroup函数、sort和一些映射到达那里,但必须有更简单的方法,不是吗?这似乎是一个普遍有用的功能。

4

1 回答 1

7

当只有两种情况时,您可以将它们映射到布尔值并使用Data.List.partition.

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

在一般情况下,您可以将 aData.Map与列表或集合一起用作值类型。您可以使用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])]
于 2011-07-25T01:03:10.443 回答