elmcraft / core-extra

Utility functions for an improved experience with elm/core
https://package.elm-lang.org/packages/elmcraft/core-extra/latest/
Other
22 stars 10 forks source link

Add Array.Extra.getMany #33

Open gampleman opened 5 months ago

gampleman commented 5 months ago

getMany : Array Int -> Array a -> Maybe (Array a)

Like Array.get, but retrieves a number of elements all at once.

Array.fromList ["Alice", "Ben", "Charlie", "David"]
    |> getMany (Array.fromList [1, 3])
    --> Just (Array.fromList [ "Ben", "David" ])

Motivating use case

A list (or array) of indices is a fairly natural way to abstractly store a particular ordering of an array. Once you're done processing, you want to have a way to materialise the ordering.

Rationale

The way one would implement this is relatively straightforward, but mostly marred by excessive Maybe handling:

getMany indices array =
   Array.foldr (\index ->
      Maybe.map2 (::) (Array.get idea array)
   ) (Just []) indices
        |> Maybe.map Array.fromList

or some such. Not terrible, but easy to get the ordering wrong (which maybe I have, I didn't check).

Design alternatives

  1. It makes sense for this to be on Array and for the second argument to be an Array, but the first argument could easily be a list and so could the return type. It sort of seems more consistent for everything to be an Array :shrug:.
  2. We could easily make it so that it would not return a Maybe if an index wasn't found. Instead the missing index would simply be ignored. It would be relatively easy to detect that case, since then Array.length return /= Array.length indices.
miniBill commented 5 months ago

My vote is for both "List" and "return List a instead of Maybe (List a)"

sebsheep commented 4 months ago

I'd advocate for providing both signatures:

Like @miniBill , I'd tend to not wrap into a Maybe since:

Having the two functions allows the developper to choose what fits most to its use case.