Book Image

Elixir Cookbook

By : Paulo Pereira
Book Image

Elixir Cookbook

By: Paulo Pereira

Overview of this book

Table of Contents (16 chapters)
Elixir Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Mapping and reducing enumerables


In Elixir, protocols are a way to achieve polymorphism. The Enum and Stream modules work on data types that implement the Enumerable protocol, so the behavior of both modules becomes similar. In this context, polymorphism might be perceived as a common API to interact with different modules.

All Enum module functions accept a collection as one of the arguments, and two very common operations in collections are map and reduce. With map, we perform some kind of operation on every element of a given collection, and with reduce, the whole collection is reduced into a value.

Getting ready

For this recipe, we will use a new IEx session. To start it, type iex in your console.

How to do it…

To perform map and reduce on a collection, we will be following these steps:

  1. We will start by creating a list with numbers from 1 to 9

    iex(1)> my_list = Enum.to_list(1..9)
    [1, 2, 3, 4, 5, 6, 7, 8, 9]
    
  2. Create an anonymous function to map the collection:

    iex(2)> my_map_function_one...