typestar

Maps in Elixir

One exoplanet record read four ways: dot, brackets, Map.get, and a pattern.

# A map literal; atom keys get the key: value shorthand.
planet = %{name: "Kepler-62f", radius: 1.41, habitable: true}

IO.puts("name: #{planet.name}")
IO.puts("radius: #{planet[:radius]} Earths")
IO.puts("moons: #{Map.get(planet, :moons, "unknown")}")

# Matching on a partial shape pulls fields out by name.
%{name: n, habitable: h} = planet
IO.puts("#{n} habitable? #{h}")

How it works

  1. %{name: ..., radius: ...} uses the atom-key shorthand to build the map.
  2. Dot access wants the key present; planet[:radius] and Map.get tolerate misses, one with a default.
  3. %{name: n, habitable: h} = planet matches part of the shape and ignores the rest.

Keywords and builtins used here

The run, in numbers

Lines
10
Characters to type
375
Tokens
94
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 75 seconds.

Type this snippet

Step 1 of 3 in Maps & structs, step 10 of 27 in Language basics.

← Previous Next →

Maps in other languages