- 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.
- JavaScript全程指南
- Visual FoxPro程序設(shè)計(jì)教程
- C# 從入門到項(xiàng)目實(shí)踐(超值版)
- 動(dòng)手玩轉(zhuǎn)Scratch3.0編程:人工智能科創(chuàng)教育指南
- 網(wǎng)頁設(shè)計(jì)與制作教程(HTML+CSS+JavaScript)(第2版)
- Java面向?qū)ο蟪绦蜷_發(fā)及實(shí)戰(zhàn)
- Python 3破冰人工智能:從入門到實(shí)戰(zhàn)
- 自制編程語言
- 大數(shù)據(jù)分析與應(yīng)用實(shí)戰(zhàn):統(tǒng)計(jì)機(jī)器學(xué)習(xí)之?dāng)?shù)據(jù)導(dǎo)向編程
- R語言與網(wǎng)絡(luò)輿情處理
- Getting Started with Python
- Swift 2 Design Patterns
- Spring Boot 2+Thymeleaf企業(yè)應(yīng)用實(shí)戰(zhàn)
- Python語言及其應(yīng)用(第2版)
- Lucene 4 Cookbook