elm-community / list-extra

Convenience functions for working with List.

Home Page:http://package.elm-lang.org/packages/elm-community/list-extra/latest

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

New function for finding, which returns a mapped value

Keyamoon opened this issue · comments

I have encountered many scenarios where a function like the following would have been useful:

mapFind : (a -> Maybe b) -> List a -> Maybe b

It's similar to find but it returns a mapped value. Suppose you want to use an expensive function, let's say factorial, on each element to find the first element with a factorial larger than 1000. But you want the resulting factorial rather than the element in the list. Using the existing find function, you'd have to call the factorial function twice, once for finding the element, and once for mapping the resulting Maybe value. With something like the mapFind function above, we could avoid the extra computation:

mapFind
  (\x ->
    let
      y =
        factorial x
    in
      if y > 1000 then Just y else Nothing
  )
  xs

This is a contrived example but I have encountered similar situations a couple of times now, so I thought it would make for a good addition to List.Extra.

I could make the pull request, but I wanted to get some feedback first. I'm also not sure about the name mapFind. This name is similar to how List.filterMap was named, which maps elements first and then filters them. Perhaps it should be called mappedFind instead, but then it wouldn't be consistent with List.filterMap. So I don't know, what should we call it?

Theres already a PR for findMap over here: #82 if you would like to join the discussion.

Oops. I forgot to check pull requests. I'll close this and continue conversation there.