导入
枚举:处理集合
学习如何使用 Enum 模块实现的各种功能。
简介
Enum 模块是 Elixir 中使用最频繁的库之一。我们可以用它来遍历、过滤、合并、拆分以及以其他方式操作集合。以下是一些常见操作:
- 将任意集合转换为列表:
1iex> list = Enum.to_list 1..5 2[1, 2, 3, 4, 5]
- 连接集合:
1iex> Enum.concat([1,2,3], [4,5,6]) 2[1, 2, 3, 4, 5, 6] 3iex> Enum.concat([1,2,3], 'abc') 4[1, 2, 3, 97, 98, 99]
- 创建新集合,其元素是原集合元素的某种函数结果:
1iex> Enum.map(list, &(&1 * 10)) 2[10, 20, 30, 40, 50]
1iex> Enum.map(list, &String.duplicate("*", &1)) 2["*", "**", "***", "****", "*****"]
- 按位置或条件筛选元素:
1iex> Enum.at(10..20, 3) 213 3iex> Enum.at(10..20, 20) 4nil
1iex> Enum.at(10..20, 20, :no_one_here) 2:no_one_here
1iex> require Integer # 用于访问 is_even 函数 2Integer 3iex> Enum.filter(list, &Integer.is_even/1) 4[2, 4] 5iex> Enum.reject(list, &Integer.is_even/1) 6[1, 3, 5]
- 对元素进行排序和比较:
1iex> Enum.sort ["there", "was", "a", "crooked", "man"] 2["a", "crooked", "man", "there", "was"]
1iex> Enum.max ["there", "was", "a", "crooked", "man"] 2"was" 3iex> Enum.max_by ["there", "was", "a", "crooked", "man"], &String.length/1 4"crooked"
- 拆分集合:
1iex> Enum.take(list, 3) 2[1, 2, 3] 3iex> Enum.split(list, 3) 4={[1, 2, 3], [4, 5]} 5iex> Enum.split_while(list, &(&1 < 4)) 6={[1, 2, 3], [4, 5]}
- 合并集合:
1iex> Enum.join(list) 2"12345" 3iex> Enum.join(list, ", ") 4"1, 2, 3, 4, 5"
- 谓词操作:
1iex> Enum.all?(list, &(&1 < 4)) 2false 3iex> Enum.any?(list, &(&1 < 4)) 4true 5iex> Enum.member?(list, 4) 6true 7iex> Enum.empty?(list) 8false
- 合并多个集合:
1iex> Enum.zip(list, [:a, :b, :c]) 2[{1, :a}, {2, :b}, {3, :c}] 3iex> Enum.with_index(["once", "upon", "a", "time"]) 4[{"once", 0}, {"upon", 1}, {"a", 2}, {"time", 3}]
- 将集合元素折叠成单一值:
1iex> Enum.reduce(1..100, &(&1 + &2)) 25050
1iex> Enum.reduce(["now", "is", "the", "time"], fn word, longest -> 2...> if String.length(word) > String.length(longest) do 3...> word 4...> else 5...> longest 6...> end 7...> end) 8"time"
关于排序的一点说明
在 sort 示例中,我们使用了如下代码:
1iex> Enum.sort ["there", "was", "a", "crooked", "man"], 2...> &(String.length(&1) <= String.length(&2))
如果希望排序保持稳定,必须使用 <= 而不是仅使用 <。
现在我们来通过终端练习一下。
Terminal