%{
1 => 2,
{"tuple"} => %{this: :that},
["even", "lists"] => ~r/regex/,
:foo => <<?h, ?e, ?l, ?l, ?o>>
}
defmodule Car do
@enforce_keys [:make]
defstruct [:model, :make]
end
a = ["foo", %{bar: %{baz: "wibble"}}, [1, 2, 3, 4]]
[_, %{bar: %{baz: value}}, [1 | tail]] = a
In Elixir, functions are uniquely identified by name and arity. Within a given name/arity, you can define multiple function heads that use pattern matching and guards. At call time, Elixir picks the right clause by trying the heads in order until one matches the arguments’ shape.
def foo(), do: "empty"
def foo(a) when is_number(a) do
"you chose #{n}"
end
def foo(%{env: :prod} = _state, blah), do: "..."
def foo([]), do: "..."
def foo([h | t]), do: something_recursive
def foo(%User{} = user) # here we match a struct
defmodule Cleaner do
def clean_text(text) do
text
|> String.trim()
|> String.downcase()
|> String.replace(~r/[^a-z0-9\s]/, "")
|> String.split(~r/\s+/, trim: true)
|> Enum.uniq()
|> Enum.sort()
end
end
vs
Enum.sort(
Enum.uniq(
String.split(
String.replace(
String.downcase(
String.trim(" Hello, HELLO... World!! World ")
),
~r/[^a-z0-9\s]/,
""
),
~r/\s+/,
trim: true
)
)
)
Bogdan/Björn's Erlang Abstract Machine
The browser renders HTML sent from the server.
User interactions (clicks, form changes, etc.) send events over a persistent WebSocket connection to the server.
The server updates the state, re-renders the relevant HTML diff, and pushes only those changes back to the browser.
{1, 2, 3}
{:ok, "something"}
{:error, "some error message"}
{:can, 1, ["contain"], AnythingYouLike}
[this: "that", foo: "bar"] => [{:this, "that"}, {:foo, "bar"}]