Intro

Control flow

Comprehensions

for x <- [1, 2, 3], y <- [2, 3, 4], rem(y, 2) == 0 do
  x * y
end
#=> [2, 4, 4, 8, 6, 12]
for <<r::8, g::8, b::8 <- pixels>>, do: {r, g, b}

into

for <<c <- " hello world ">>, c != ?\s, into: "", do: <<c>>
#=> "helloworld"

uniq

for x <- [1, 1, 2, 3], uniq: true, do: x * 2
#=> [2, 4, 6]

reduce

for <<x <- "AbCabCABc">>, x in ?a..?z, reduce: %{} do
  acc -> Map.update(acc, <<x>>, 1, & &1 + 1)
end
#=> %{"a" => 1, "b" => 2, "c" => 1}

with

with {:ok, map} <- do_something do
  on_success
end

Enum

Stream

cycle

Stream.cycle([1, 2, 3])
|> Enum.take(5)
#=> [1, 2, 3, 4, 5]

repeatedly

Stream.repeatedly(&:rand.uniform/0)
|> Enum.take(3)
#=> [0.6148287886796542, 0.3662689171313852, 0.6596815231166095]

iterate

Stream.iterate(0, &(&1 + 1))
|> Enum.take(5)
#=> [0, 1, 2, 3, 4]

unfold

Stream.unfold(5, fn
  0 -> nil
  n -> {n, n - 1}
end) |> Enum.to_list()
#=>[5, 4, 3, 2, 1]
Stream.unfold({0, 1}, fn {f1, f2} -> {f1, {f2, f1 + f2}} end) |> Enum.take(7)
#=> [0, 1, 1, 2, 3, 5, 8]

resource

Stream.resource(
  fn -> File.open!("sample") end,
  fn file ->
    case IO.read(file, :line) do
      data when is_binary(data) -> {[data], file}
      _ -> {:halt, file}
    end,
    fn file -> File.close(file) end
)

Strings

Binaries

<< 12.3::big-signed-float-size(32) >>
<< a::binary-size(32) >>

Options

Qualifiers

Using IOLists

list = ["abc", "def"]
IO.iodata_to_binary(list)
#=> "abcdef"

Gettext

Debugging

pry

require IEx; IEx.pry

breakpoints

command description
binding shows all variables in scope
break!(fun) define a new breakpoint for Mod.fun/arity
breaks prints all breakpoints and their IDs
continue continue the code execution
respawn starts a new shell
whereami show the file name, line and the code being executed

Random Numbers

Timer

:timer.send_interval(time, message)
:timer.send_after(time, message)
:timer.sleep(time)
Process.sleep(time)

Releases

Deployment