Learn/Elixir/5. Loops
Lesson 5 of 8
Sign in

Elixir, lesson 5

Loops

Most languages repeat work with for and while loops that change a counter on every pass. Elixir has no such loops, because its values never change. Instead, you describe what should happen to each item of a collection, and Elixir does the walking for you.

Ranges and Enum.each

A range like 1..5 stands for the numbers 1, 2, 3, 4, 5. The Enum module holds dozens of functions that work on ranges, lists and maps. Enum.each/2 runs a function once per item:

fn i -> ... end is an anonymous function: a small function without a name that you pass around like any other value. Here Enum.each calls it with 1, then , then . A range can count down too: goes 5, 4, 3, 2, 1 (the is the step).

2 exercises to try what you just read.

Exercise 1

Times table

Press Ctrl Enter or Check to test your code.

Exercise 2

Savings goal

Press Ctrl Enter or Check to test your code.

2
3
5..1//-1
//-1

for comprehensions

for looks like a loop, but it builds and returns a list:

IO.inspect prints any value in Elixir syntax, which is handy for lists. You can add a filter after the generator: for n <- 1..10, rem(n, 2) == 0, do: n keeps only the even numbers.

Carrying a value along: Enum.reduce

What about a running total? Without a variable to update, you pass the total forward. Enum.reduce/3 takes a collection, a starting value (the accumulator) and a function. The function gets each item plus the current accumulator and returns the next accumulator:

Stopping early: Enum.reduce_while

A while loop usually stops as soon as something becomes true. Enum.reduce_while/3 does the same: your function returns {:cont, acc} to keep going or {:halt, acc} to stop right away.

Recursion

Under the hood, all of this is recursion: a function that calls itself with a smaller problem until it reaches a stopping case. You will write your own named functions in the next lesson; here is a taste:

The first clause stops at 0; the second prints and calls itself with n - 1.

Reading every line of input

IO.stream(:stdio, :line) gives you the remaining input as a stream of lines, which any Enum function can walk through. Each line still ends with "\n", so trim it before converting.

Further reading

  • Getting started: Recursion
  • Getting started: Enumerables and streams
  • Getting started: Comprehensions
  • Enum.reduce_while/3

Read a whole number n and print its times table from 1 to 10, one line each, in this form:

Input: one line with n (it may be 0 or negative). Output: exactly ten lines.

You are saving up for a bike. Read your savings goal, then a list of deposits. Count how many deposits it takes for the total to reach the goal (equal counts as reached). Stop looking at deposits as soon as you get there.

Input: the first line is the goal (at least 1). Each following line is one deposit (a whole number of 0 or more). There may be no deposits at all.

Output: if the goal is reached, print Goal reached! Deposits used: K. Otherwise print Short by X. where X is how much is still missing.

prints Goal reached! Deposits used: 3

Enum.each(1..3, fn i ->
  IO.puts("Lap #{i}")
end)
squares = for n <- 1..5, do: n * n
IO.inspect(squares)   # [1, 4, 9, 16, 25]
total = Enum.reduce([4, 8, 15], 0, fn price, sum -> sum + price end)
IO.puts(total)   # 27
# Add numbers until the sum passes 10.
Enum.reduce_while([3, 4, 5, 6], 0, fn n, sum ->
  if sum + n > 10, do: {:halt, sum + n}, else: {:cont, sum + n}
end)
# returns 12 and never looks at 6
defmodule Count do
  def down(0), do: IO.puts("Go!")
  def down(n) do
    IO.puts(n)
    down(n - 1)
  end
end

Count.down(3)   # 3, 2, 1, Go!
7 x 1 = 7
7 x 2 = 14
...
7 x 10 = 70
100
30
50
40
10