Enum.map
can be used to change the values of the odd elements of a list:
iex(13)> [1,2,3,4,5,6] |> Enum.map_every(2, &(&1 + 100))
[101, 2, 103, 4, 105, 6]
However it appears that there needs to be an offset of 1
to do the same for the even elements of the list.
Is there a function that can directly map_every
even number?
There is no function that does this.
However, it can be achieved with 2 lines by shifting the array and using Enum.map_every/3
iex(1)> [head | tail] = [1,2,3,4,5,6]
[1, 2, 3, 4, 5, 6]
iex(2)> [head | Enum.map_every(2, tail, &(&1 + 100))]
[1, 102, 3, 104, 5, 106]
You could also build a function like below. It will start mapping at the provided nth
, instead of the first element:
def map_every_alt(enumerable, nth, fun) when nth > 0 do
Enum.take(enumerable, nth - 1) ++
Enum.map_every(Enum.drop(enumerable, nth - 1), nth, fun)
end
While shifting the original list works, I don't really think that's the proper way to go. Whether one needs the even elements to be updated, this might be done explicitly:
require Integer
[1,2,3,4,5,6]
|> Enum.map_every(1, &(if Integer.is_even(&1), do: &1 + 100, else: &1))
#⇒ [1, 102, 3, 104, 5, 106]
The same applies to any cumbersome condition: one just calls Enum.map_every/3
with nth
argument set to 1
and performs an additional check in the reducer, returning either modified value, or the original one.
The the condition should be applied to an index , wrap the input using Enum.with_index/1
[1,2,3,4,5,6]
|> Enum.with_index
|> Enum.map_every(1, fn {e, idx} ->
if Integer.is_even(idx), do: e + 100, else: e
end)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.