Run this notebook

Use Livebook to open this notebook and explore new ideas.

It is easy to get started, on your machine or the cloud.

Click below to open and run it in your Livebook at .

(or change your Livebook location)

# For, Map and Reduce ## What's a list comprehension? The command 'for' in Elixir is a list comprehension. The result of a for is a list. For instance, in the example below, i goes from one to ten. The result is a list containing each value of i multiplied by 10. ```elixir for i <- 1..10 do i * 10 end ``` You could do the same using Enum.map/2. ```elixir 1..10 |> Enum.map(fn x -> x * 10 end) ``` If, instead, you wanted result of the sum of all the values of the list, you would have two options. The first one is to usem Enum.sum() to sum all values of the resulting list. ```elixir 1..10 |> Enum.map(fn x -> x * 10 end) |> Enum.sum() ``` The second option is to use Enum.reduce/2: ```elixir 1..10 |> Enum.reduce(fn x, accum -> x * 10 + accum end) ``` What if I wanted to multiply all values of the resulting list? The following solution would not work. ```elixir 1..10 |> Enum.reduce(fn x, accum -> x * 10 * accum end) ``` Because this is the value of 10 *... * 100: ```elixir 10 * 20 * 30 * 40 * 50 * 60 * 70 * 80 * 90 * 100 ``` The correct way is: ```elixir 1..10 |> Enum.reduce(1, fn x, accum -> x * 10 * accum end) ``` What's the difference between Enum.reduce/2 and Enum.reduce/3? ## Back to for For allows you to have more than one generator (the 'i <- 1..10' part): ```elixir for i <- 1..3, j <- ["Brasil", "Mexico", "Angola"] do {:number, i, :country, j} end ``` You can also add filters: ```elixir require Integer for i <- 1..3, j <- ["Brasil", "Mexico", "Angola"], Integer.is_even(i), String.starts_with?(j, "B") do {:number, i, :country, j} end ``` There are many more things that you can do with for, map and reduce. Explore Elixir's docs to learn more!
See source

Have you already installed Livebook?

If you already installed Livebook, you can configure the default Livebook location where you want to open notebooks.
Livebook up Checking status We can't reach this Livebook (but we saved your preference anyway)
Run notebook

Not yet? Install Livebook in just a minute

Livebook is open source, free, and ready to run anywhere.

Run on your machine

with Livebook Desktop

Run in the cloud

on select platforms

To run on Linux, Docker, embedded devices, or Elixir’s Mix, check our README.

PLATINUM SPONSORS
SPONSORS
Code navigation with go to definition of modules and functions Read More ×