Reading — step 1 of 5
Learn
~1 min readControl Flow
Elixir has no traditional for loop — there's no mutable counter to advance. Instead you use recursion (with the Enum module wrapping common patterns).
Recursion:
defmodule Sum do
def to_n(0), do: 0
def to_n(n), do: n + to_n(n - 1)
end
IO.puts Sum.to_n(5) # 15
Multiple function clauses with different patterns let recursion read like math definitions.
Enum is the everyday tool for collection iteration:
Enum.map([1, 2, 3], fn n -> n * 2 end) # [2, 4, 6]
Enum.filter([1, 2, 3, 4], &(&1 > 2)) # [3, 4]
Enum.reduce([1, 2, 3], 0, &+/2) # 6
Enum.sum(1..100) # 5050
&(&1 + 1) is the capture form — shorthand for fn x -> x + 1 end.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…