- Mastering Elixir
- André Albuquerque Daniel Caixinha
- 282字
- 2021-08-05 10:42:48
Eager processing with the Enum module
Having seen how recursion works in Elixir, we'll now show some examples of the abstractions that are built on top of it. We'll explore the Enum module, which contains a set of functions to work on collections. We've already seen some examples of collections in the Elixir's data types section, such as lists or maps. More generally, we can use the Enum module on collections that implement the Enumerable protocol.
Taking the two examples from our Recursion section, let's see how they become incredibly simple to implement using the Enum module:
iex> Enum.map([2, 4, 6], &(&1 * 2))
[4, 8, 12]
iex> Enum.reduce([1, 2, 3], 1, &(&1 * &2))
6
The map function receives a collection and a lambda, and returns a new list where the lambda is applied to each element of the collection.
The reduce function receives a collection, an accumulator, and a lambda. The lambda receives the current element of the collection and the accumulator, and the result of this lambda is the accumulator for the following iteration. At the end of the iteration, reduce returns the final accumulator value.
iex> require Integer
Integer
iex> Enum.map([1, 2, 3], &Integer.is_even/1)
[false, true, false]
You'll see the Enum module being used in the application that we'll build throughout the book. For further usage of the Enum module, check its documentation at https://hexdocs.pm/elixir/Enum.html.
- SoapUI Cookbook
- GraphQL學(xué)習(xí)指南
- Rust編程:入門、實(shí)戰(zhàn)與進(jìn)階
- 區(qū)塊鏈架構(gòu)與實(shí)現(xiàn):Cosmos詳解
- AIRAndroid應(yīng)用開發(fā)實(shí)戰(zhàn)
- 數(shù)據(jù)庫(kù)系統(tǒng)原理及MySQL應(yīng)用教程
- Java程序設(shè)計(jì)與計(jì)算思維
- 云原生Spring實(shí)戰(zhàn)
- UI智能化與前端智能化:工程技術(shù)、實(shí)現(xiàn)方法與編程思想
- 秒懂設(shè)計(jì)模式
- 學(xué)習(xí)正則表達(dá)式
- Scala程序員面試算法寶典
- 精通Python自動(dòng)化編程
- Python Data Science Cookbook
- 快速入門與進(jìn)階:Creo 4·0全實(shí)例精講