Lists
7 min · Elixir
Elixir's linked lists — head, tail, and index-free traversal.
Enemy 1 of 5
Lists are built from head and tail
An Elixir list is fundamentally a linked structure: it's either empty, or it's a "head" (the first element) joined to a "tail" (the rest of the list, itself a list). The `[head | tail]` syntax expresses that structure directly, and `[1, 2, 3]` is just convenient shorthand for the fully spelled-out cons form. This linked-list foundation is very different from an array, where every element sits at a directly-addressable numbered slot in memory — a distinction that matters once you think about performance, since some operations that are instant on an array (like jumping straight to the middle) require walking element-by-element on a linked list.
`hd/1` ("head") returns a list's first element; its counterpart `tl/1` ("tail") returns everything after the first element, as a new list. Calling `hd` or `tl` on an empty list raises an error, since there's no head or tail to return — a common beginner bug is forgetting to handle the empty-list case when writing recursive code that walks a list this way.
Loading editor...