Search code examples
numberselixirenumerable

Enum.map_every even number


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?


Solution

  • 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)