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 Result.Extra.collect #25

Open gampleman opened 9 months ago

gampleman commented 9 months ago

collect : List (Result e a) -> Result (List e) (List a)

Particularly useful for validation, it collects all the errors in the list, so they can all be shown at once to the user.

Motivating use case

Validation almost always needs this, but pretty much any library where we want to show good error messages needs to not loose information.

Rationale

This tends to be in practice more useful than Result.Extra.combine, as when using Result, we actually care about the error type.


collect : List (Result e a) -> Result (List e) (List a)
collect =
  List.foldr (\ra soFar -> 
    case (ra, soFar) of
       (Err x, Err y) ->
         Err (x :: y)

       (Ok _, Err _) ->
          soFar

       (Err x, Ok _) ->
          Err [ x ]

       (Ok x, Ok y) ->
          Ok (x :: r)

  ) (Ok [])

or some such. Not terrible to write, but not exactly a handy one-liner either.

Name

collect is just a spitball idea, moderate bike-shedding welcome.

miniBill commented 7 months ago

classify? I don't love it though

miniBill commented 4 months ago

Also, if you do this you should have it be List (Result e a) -> Result (e, List e) (List a)