简体   繁体   English

Enum.map_每个偶数

[英]Enum.map_every even number

Enum.map can be used to change the values of the odd elements of a list: Enum.map可用于更改列表的奇数元素的值:

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. 但是,似乎需要为列表的偶数元素设置1的偏移量。

Is there a function that can directly map_every even number? 是否有可以直接map_every偶数的函数?

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 但是,通过移动数组并使用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: 它将在提供的nth而不是第一个元素处开始映射:

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. 这同样适用于任何麻烦的情况:只需将nth参数设置为1 Enum.map_every/3进行调用, Enum.map_every/3执行附加检查,返回修改后的值或原始值。


The the condition should be applied to an index , wrap the input using Enum.with_index/1 该条件应应用于索引 ,使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM