官术网_书友最值得收藏!

  • 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.

We haven't yet covered protocols. We will do so in the Protocols section.

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.

We're using the capture operator to define a lambda. As we've previously hinted, you can also use it to capture named functions. In the following example, we're using the Integer.is_even/1 function to check which numbers are even in a collection:

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.

主站蜘蛛池模板: 栖霞市| 江山市| 万山特区| 独山县| 江孜县| 南安市| 灵川县| 东阳市| 繁昌县| 栾川县| 辽中县| 清苑县| 扶余县| 靖安县| 农安县| 龙井市| 磐安县| 蒙自县| 如东县| 广昌县| 丰镇市| 稻城县| 绥宁县| 天台县| 沙湾县| 峨眉山市| 潮安县| 五指山市| 大安市| 桐柏县| 东乡族自治县| 蒲城县| 长宁县| 和田县| 阿瓦提县| 蒙城县| 凤冈县| 东乌珠穆沁旗| 德格县| 阿拉善右旗| 米林县|