簡體   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