Search code examples
elm

Partition list into more than 2 parts


So I want to partitision a List ItemModel in Elm into List (List ItemModel). List.partition only makes the list into two lists.

I wrote some code that makes the list into the parts I want (code below).

But it's not as nice of a solution as I'd like, and since it seems like an issue many people would have, I wonder are there better examples of doing this?

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 ->
                []

Solution

  • The returned list maps directly from the filters parameter, so it's actually pretty straightforward to do this using just List.map and List.filter (which is what you're really doing since you're discarding the remainder list returned from List.partition):

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