因此,我想将榆树中的List ItemModel
分成List (List ItemModel)
。 List.partition
只将列表分为两个列表。
我写了一些代码,使列表成为我想要的部分(下面的代码)。
但是它并不像我想的那样好,而且因为它似乎是很多人都会遇到的问题,我想知道有更好的例子吗?
partition : List (ItemModel -> Bool) -> List ItemModel -> List (List ItemModel)
partition filters models =
let
filterMaybe =
List.head filters
in
case filterMaybe of
Just filter ->
let
part =
Tuple.first (List.partition filter models)
in
part :: (partition (List.drop 1 filters) models)
Nothing ->
[]
返回的列表直接映射到filters
参数,所以使用List.map
和List.filter
实际上非常简单(这是你正在做的事情,因为你丢弃了从List.partition
返回的剩余列表):
multifilter : List (a -> Bool) -> List a -> List (List a)
multifilter filters values =
filters |> List.map(\filter -> List.filter filter values)
重复分区需要使用每个步骤中的剩余部分作为下一步的输入。这与通过几个滤波器对相同序列的简单重复过滤不同。
在Haskell中(这个问题最初被标记为),
partitions :: [a -> Bool] -> [a] -> [[a]]
partitions preds xs = go preds xs
where
go [] xs = []
go (p:ps) xs = let { (a,b) = partition p xs } in (a : go ps b)
也就是说,
partitions preds xs = foldr g (const []) preds xs
where
g p r xs = let { (a,b) = partition p xs } in (a : r b)
要么
-- mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
partitions preds xs = snd $ mapAccumL (\xs p -> partition (not . p) xs) xs preds
测试:
> partitions [ (<5), (<10), const True ] [1..15]
[[1,2,3,4],[5,6,7,8,9],[10,11,12,13,14,15]]
不像重复过滤,
> [ filter p xs | let xs = [1..15], p <- [ (<5), (<10), const True ]]
[[1,2,3,4],[1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]]