分区列表分为2部分以上

问题描述 投票:1回答:2

因此,我想将榆树中的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 ->
                []
elm
2个回答
1
投票

返回的列表直接映射到filters参数,所以使用List.mapList.filter实际上非常简单(这是你正在做的事情,因为你丢弃了从List.partition返回的剩余列表):

multifilter : List (a -> Bool) -> List a -> List (List a)
multifilter filters values =
    filters |> List.map(\filter -> List.filter filter values)

1
投票

重复分区需要使用每个步骤中的剩余部分作为下一步的输入。这与通过几个滤波器对相同序列的简单重复过滤不同。

在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]]
© www.soinside.com 2019 - 2024. All rights reserved.