typestar

Lists and cons in Elixir

Building a shipping route by prepending, splicing, and walking head and tail.

# Lists are linked cells: | prepends in one step, ++ splices two lists.
ports = ["Reykjavik", "Nuuk"]
route = ["Halifax" | ports] ++ ["Tromso"]

IO.inspect(route, label: "route")
IO.puts("depart from #{hd(route)}")
IO.puts("then: #{Enum.join(tl(route), " -> ")}")
IO.puts("legs to sail: #{length(route) - 1}")

How it works

  1. ["Halifax" | ports] prepends in constant time; ++ splices "Tromso" onto the end.
  2. hd and tl split the route into the first stop and the rest.
  3. length(route) - 1 counts the legs between the port calls.

Keywords and builtins used here

The run, in numbers

Lines
8
Characters to type
309
Tokens
92
Three-star pace
75 tpm

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

Type this snippet

Step 1 of 3 in Lists & tuples, step 7 of 27 in Language basics.

← Previous Next →

Lists and cons in other languages