wanton7
Is there something like Enum.find_with_index?
I’m trying to look at the docs but I couldn’t find a function that would return element with its index. Is there such a function for lists that doesn’t involve creating a new list? I want to do modify the the element if it exists and then use List.replace_at to replace it. But because I don’t have the index, I first have use Enum.find_index to get the index and then if it’s not nil, then I have to use Enum.at to get the element itself.
Edit: added code
defp edit_if_exists(elements, id, fun) do
case elements |> Enum.find_index(&(&1.id == id)) do
nil ->
elements
idx ->
element = elements |> Enum.at(idx); # Want to know if I can some how avoid this
elements |> List.replace_at(idx, fun.(element))
end
end
Marked As Solved
LostKobrakai
Enum.reduce_while(list, {:not_found, 0}, fn el, {:not_found, index} ->
if el.id == id, do: {:halt, {:found, index, el}}, else: {:cont, {:not_found, index + 1}}
end)
Also Liked
KristerV
this thread would greatly benefit from example code. sounds like a XY problem.
LostKobrakai
Can you explain why you need to work with indexes on a list? Often when you need indexed access a list in not the best datatype to use.
LostKobrakai
Enum.reduce_while can do that. That’s what find_index is based on.
wanton7
Enum.with_index creates a new list
csadewa
List.replace_at also create a new list, elixir being immutable will always return new data structure for modification.
Alternatively, if you want to focus on replace an element without considering using index, you could just use Enum.map, and change elem if it’s match your search criteria







