elm-community / list-extra

Convenience functions for working with List.
http://package.elm-lang.org/packages/elm-community/list-extra/latest
MIT License
135 stars 58 forks source link

Proposal for `combinations` #127

Closed janwirth closed 4 years ago

janwirth commented 4 years ago

I built a function that creates all possible pairs of items in a list. This is great for determining relations / calculating metrics between different items.

combinations : List a -> List ( a, a )
combinations els =
    case els of
        [] ->
            []

        next :: rest ->
            combinations_ next [] rest

combinations_ : a -> List ( a, a ) -> List a -> List ( a, a )
combinations_ next soFar rest =
    let
        -- make a pair with the current item and all the other items in the list
        soFar_ =
            soFar ++ List.map (Tuple.pair next) rest
    in
    case rest of
        [] ->
            soFar

        next_ :: rest_ ->
            -- take the next item and repeat
            combinations_ next_ soFar_ rest_
combinations [1, 2, 3] --> [(1,2), (1,3), (2,3)]
Chadtech commented 4 years ago

Hey @FranzSkuffka ,

Thanks for the submission, but I think we already have this function, except under the name uniquePairs

janwirth commented 4 years ago

😅