Range Over Built in Elixir

To sum the numbers in a list and iterate over different data structures using the for loop and pattern matching.

defmodule Example do
  def main do
    # Here we use pattern matching to sum the numbers in a list. Tuples work like this too.
    nums = [2, 3, 4]
    sum = Enum.reduce(nums, 0, fn num, acc -> acc + num end)
    IO.puts("sum: #{sum}")

    # pattern matching on lists provides both the index and value for each entry.
    # If you don't need the index, you can ignore it with `_`.
    Enum.with_index(nums)
    |> Enum.each(fn {num, i} ->
      if num == 3 do
        IO.puts("index: #{i}")
      end
    end)

    # pattern matching on maps iterates over key/value pairs.
    kvs = %{"a" => "apple", "b" => "banana"}
    Enum.each(kvs, fn {k, v} ->
      IO.puts("#{k} -> #{v}")
    end)

    # pattern matching can also iterate over just the keys of a map.
    Map.keys(kvs)
    |> Enum.each(&IO.puts("key: #{&1}"))

    # pattern matching on strings iterates over Unicode code
    # points. The first value is the starting byte index
    # of the codepoint and the second the codepoint itself.
    for {char, byte_index} <- String.to_charlist("go") |> Enum.with_index do
      IO.puts("#{byte_index} #{char}")
    end
  end
end

Example.main()

To run the program, save the code in a file, let’s say example.exs, and use the Elixir command to execute it.

$ elixir example.exs
sum: 9
index: 1
a -> apple
b -> banana
key: a
key: b
0 103
1 111

Now that we can run and build basic Elixir programs, let’s move on to learn more about the language.