- 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.
- DBA攻堅指南:左手Oracle,右手MySQL
- Pandas Cookbook
- Cross-platform Desktop Application Development:Electron,Node,NW.js,and React
- Learning RxJava
- Java Web開發(fā)之道
- MySQL數(shù)據(jù)庫管理與開發(fā)(慕課版)
- Python 3破冰人工智能:從入門到實戰(zhàn)
- Flux Architecture
- PHP+Ajax+jQuery網(wǎng)站開發(fā)項目式教程
- PHP編程基礎(chǔ)與實踐教程
- Visual FoxPro 6.0程序設(shè)計
- Python趣味編程與精彩實例
- Machine Learning for Developers
- 測試架構(gòu)師修煉之道:從測試工程師到測試架構(gòu)師
- Python預測之美:數(shù)據(jù)分析與算法實戰(zhàn)(雙色)