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
%{name: ..., radius: ...}uses the atom-key shorthand to build the map.- Dot access wants the key present;
planet[:radius]andMap.gettolerate misses, one with a default. %{name: n, habitable: h} = planetmatches part of the shape and ignores the rest.
Keywords and builtins used here
IOMap
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.
Step 1 of 3 in Maps & structs, step 10 of 27 in Language basics.