繁体   English   中英

Enum.map_每个偶数

[英]Enum.map_every even number

Enum.map可用于更改列表的奇数元素的值:

iex(13)> [1,2,3,4,5,6] |> Enum.map_every(2, &(&1 + 100))
[101, 2, 103, 4, 105, 6]

但是,似乎需要为列表的偶数元素设置1的偏移量。

是否有可以直接map_every偶数的函数?

没有执行此操作的功能。

但是,通过移动数组并使用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]

您还可以构建如下功能。 它将在提供的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

在转移原始列表的过程中,我真的不认为这是正确的方法。 是否需要更新偶数元素,可以显式完成:

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]

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


该条件应应用于索引 ,使用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