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
["Halifax" | ports]prepends in constant time;++splices"Tromso"onto the end.hdandtlsplit the route into the first stop and the rest.length(route) - 1counts the legs between the port calls.
Keywords and builtins used here
EnumIO
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.
Step 1 of 3 in Lists & tuples, step 7 of 27 in Language basics.