當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Elixir Enum.with_index用法及代碼示例

Elixir語言中 Enum.with_index 相關用法介紹如下。

用法:

with_index(enumerable, fun_or_offset \\ 0)
@spec with_index(t(), integer()) :: [{term(), integer()}]
@spec with_index(t(), (element(), index() -> value)) :: [value] when value: any()

返回 enumerable ,每個元素都包裝在一個元組中,旁邊是它的索引。

可以接收一個函數或一個整數偏移量。

如果給出offset,它將從給定的偏移量而不是從零開始索引。

如果給出function,它將通過為每個元素和可枚舉的索引(從零開始)調用函數來索引。

例子

iex> Enum.with_index([:a, :b, :c])
[a: 0, b: 1, c: 2]

iex> Enum.with_index([:a, :b, :c], 3)
[a: 3, b: 4, c: 5]

iex> Enum.with_index([:a, :b, :c], fn element, index -> {index, element} end)
[{0, :a}, {1, :b}, {2, :c}]

相關用法


注:本文由純淨天空篩選整理自elixir-lang.org大神的英文原創作品 Enum.with_index(enumerable, fun_or_offset \\ 0)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。