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

Implement `mapMaybe` function #144

Closed ntreu14 closed 3 years ago

ntreu14 commented 3 years ago

I've implemented this a couple times in smaller personal projects of mine. I've seen this function implemented in the core libraries of Haskell and F# (called choose in F#).

You can think of this function as doing a filter and map in one. Although this is a very contrived example, you an easily imagine one more complex:

[1, 2, 3, 4, 5]
  |> List.filter (\x -> x < 3)
  |> List.map (\x -> x * x)

-- Becomes:

perhapsSquareLessThanThree x =
  if x < 3
  then x * x |> Just
  else Nothing

mapMaybe perhapsSquareLessThanThree [1, 2, 3, 4, 5]

There are also other situation where you have a function that might return a Maybe and you can directly apply that function to a list of elements to only get back a list where it is Just a.

Let me know what you think. I'd love to hear thoughts!

Chadtech commented 3 years ago

I love this function, but it is already in elm/core as List.filterMap.

ntreu14 commented 3 years ago

@Chadtech Wow, thanks for the heads up! I've never seen it called that before so didn't recognize it. I shoulda searched for the function signature.

Thanks for letting me know it already exists!