fslang-suggestions icon indicating copy to clipboard operation
fslang-suggestions copied to clipboard

Add `groupByMany: ('item -> #seq<'key>) -> #seq<'item> -> Map<'key, #seq<'item>>` for appending item to multiple groups at once

Open konst-sh opened this issue 1 year ago • 3 comments

**I propose we add a function for non-exclusive grouping of collection items into multiple groups, when the projection function returns a collection of group keys

**The existing way of approaching this problem in F# is creating this non optimized function manually:

let groupByMany (projection: 'item -> #seq<'key>) (items: seq<'item>): Map<'key, #seq<'item>> =
    (Map.empty, items)
    ||> Seq.fold(fun m item ->
        let keys = projection item
        (m, keys) 
        ||> Seq.fold(fun m key ->
            let values =
                match Map.tryFind key m with
                | Some values -> seq{yield! values; item}
                | None -> seq{item}
            Map.add key values m
        )
    )

seq{1..10}
|> groupByMany(fun i -> 
    match i%2, i%3 with
    | 0, 0 -> ["mod2"; "mod3"; "mod6"]
    | 0, _ -> ["mod2"]
    | _, 0 -> ["mod3"]
    | _, _ -> []
)
|> Map.map(fun _ s -> List.ofSeq s)

//output:
//map [
//"mod2", [ 2, 4, 6, 8, 10 ]
//"mod3", [ 3, 6, 9 ]
//"mod6", [ 6 ]
//]

Pros and Cons

**The advantages of making this adjustment to F# are having reacher collection processing capabilities of the box. Also this function is capable to exclude item from adding to any of the groups completely by returning empty key collection, in contrast to groupBy

**The disadvantages of making this adjustment to F# are - more code in standard library.

Extra information

**Estimated cost (XS, S, M, L, XL, XXL): M

**Related suggestions: Other collection processing library improvements

Affidavit (please submit!)

Please tick this by placing a cross in the box:

  • [+] This is not a question (e.g. like one you might ask on stackoverflow) and I have searched stackoverflow for discussions of this issue
  • [+] I have searched both open and closed suggestions on this site and believe this is not a duplicate
  • [+] This is not something which has obviously "already been decided" in previous versions of F#. If you're questioning a fundamental design decision that has obviously already been taken (e.g. "Make F# untyped") then please don't submit it.

Please tick all that apply:

  • [+] This is not a breaking change to the F# language design
  • [-] I or my company would be willing to help implement and/or test this

For Readers

If you would like to see this issue implemented, please click the :+1: emoji on this issue. These counts are used to generally order the suggestions by engagement.

konst-sh avatar Jul 15 '23 16:07 konst-sh