因此,我想将榆木中的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 ->
[]
答案 0 :(得分:1)
返回的列表直接从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)
答案 1 :(得分:1)
重复的分区需要使用每个步骤的剩余数据作为下一步的输入。这与通过多个过滤器对相同序列进行简单的重复过滤不同。
在Haskell(此问题最初也被标记为)
filter([1, 2, 3, 4, 5, 6], &is_odd)
也就是说,
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]]