Hello everybody, I’d like to propose adding a new accessor function to Access - Access.find/1. It works exactly like Access.at/1, but instead of accessing an element by index (with Enum.at/1), you can provide an arbitrary function that will be used with Enum.find/2 to match the proper value. I implemented this function in a project, since I needed it. Maybe it would be generally useful? The implementation is rather simple:
def find(fun) when is_function(fun, 1) do
fn(op, data, next) -> find(op, data, fun, next) end
end
defp find(:get, data, fun, next) when is_list(data) do
data |> Enum.find(fun) |> next.()
end
defp find(:get_and_update, data, fun, next) when is_list(data) do
case Enum.split_while(data, &(not fun.(&1))) do
{preceding, []} ->
{nil, preceding}
{preceding, [elem | following]} ->
case next.(elem) do
{get, update} -> {get, preceding ++ [update] ++ following}
:pop -> {elem, preceding ++ following}
end
end
end
defp find(_op, data, _fun, _next) do
raise "Access.find/1 expected a list, got: #{inspect data}"
end
Michał.
--
You received this message because you are subscribed to the Google Groups
"elixir-lang-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/elixir-lang-core/434356A9-EF6A-47F9-BEEB-0C7D4054B2F1%40muskala.eu.
For more options, visit https://groups.google.com/d/optout.
signature.asc
Description: Message signed with OpenPGP using GPGMail
