ELIXIR / CHAPTER 02

Lists, maps, and data shape

Intermediate

Choose a data structure and access operation that preserve the needed meaning.

By the end of this chapter

  • Decompose linked lists
  • Update a map without mutating its original
  • Distinguish missing keys from stored nil

The idea

Enter with pattern matching understood. Lists are linked sequences, so [head | tail] separates the first element from the remaining list. Prepending is a natural operation; repeated appending may repeatedly traverse existing elements. Maps associate keys with values and fit records or indexed facts. Map patterns can require a subset of keys without requiring the map to contain only those keys.

Map.put returns an updated map value while the original remains available. Map.fetch returns {:ok, value} for presence and :error for absence, which preserves the difference between missing data and a stored nil. The update syntax %{map | key: value} requires the key to exist. Choose the access contract that matches the application instead of assuming all missing-key operations behave alike.

Elixir example
original = %{count: 2}
updated = Map.put(original, :count, 7)
IO.inspect({original.count, updated.count})
Result
{2, 7}

The update produces a new map value. The original binding still describes a map whose count is two.

Try it yourself

Use Map.fetch to distinguish %{score: nil} from an empty map.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which call preserves a stored nil as a present value?