Elixir

Installation

  • Install mise
  • oh-my-zsh plugins:
  • mise install erlang
  • mise install elixir

Commands

  • iex - repl
  • iex -S mix - repl with deps
  • mix local.hex - update hex PM
  • mix deps.get - install deps
  • mix deps.update [depname] - update a dep to the latest version that fits the mix.exs constraints

Resources

Books

Courses

Syntax

https://github.com/itsgreggreg/elixir_quick_reference

# Comment

:my_atom
`nil`
name = “Josh”
“Strings have double quotes, #{name}”
range = 5..10

Collections

list = [1, 2] # stored as a linked list
length list
Enum.reverse(list)
Enum.join(list, “, “)
Enum.sort([1, 2, 3], &(&1 >= &2))
Enum.find([2, 3, 4], fn x -> rem(x, 2) == 1 end)

tuple = { :a, :b } # stored contiguous in memory

keyword_list = [{:a, “one”}, {:b, 2}]
shorthand = [a: “one”, b: 2]
Keyword.keys(keyword_list)
Keyword.get_keys(keyword_list)

map = %{:a => 1, 1 => [“list”]}
Map.keys(map)
Map.put(map, :b, 2)

defmodule Person do
  defstruct name: “”, age: 0
end
josh = %Person{name: “Josh”, age: 43}
josh.name
%Person{ josh | name: "Joshua" }

# sigils

- `~D` - Date
- `~N` - NaiveDateTime
- `~r` - escaped regex
- `~R` - unescaped regex
- `~T` - Time
- `~w` - escaped words
- `~W` - unescaped words

# map
Enum.map([1, 2, 3], fn x -> x * 2 end

# comprehensions
result = for x <- [1, 2, 3, 4, 5], x < 4, do: x * x

# groups
Enum.group_by(~w{ant buffalo cat dingo}, &String.length/1)

# map <-> list or transforming
Enum.map(%{a: 1, b: 2, c: 3}, fn {k, v} ->
  "#{k} --> #{v}"
end)
Map.new([:a, :b], fn x -> {x, x} end)
Map.new(%{a: 1, b: 2, c: 3}, fn {k, v} ->
  {k, v * 2}
end

Functions

anon_func = fn num -> num + 2 end
support_method = fn ("suspenders")   -> IO.puts "Hey big spender."
                      ("belt")         -> IO.puts "Who is the real hero?"
                      a when is_list a -> Enum.each(a, support_method)
                      _                -> IO.puts "What is this wizzardry?"
                   end

defmodule MyModule do
  def my_function(“Josh”) do
    IO.puts("Hello Josh!!!”)
  end

  def my_function(name), do: IO.puts(“Hello #{name}.”)

  defp private_func do
  end
end

Comprehensions

for num <- [1, 2, 3, 4], rem(num, 2) == 0, do: num * num