elixir [options] file.ex/file.exs iex iex -S script (e.g., iex -S mix) iex --name local iex --sname fully.qualified.name --cookie cookie.value or use $HOME/.erlang.cookie mix new / run / test / deps / etc. mix.exs specifies build details
#iex:break — back to prompt c "filename.exs" — compile r Module — reload h function_name — help i var — display type info v [n] — session history
=== !== and or not #(strict) == != && || ! #(relaxed)
, >=, <, <= +, -, *, / #(float) div, rem #(integer) binary1 <> binary2 #(concat) list1 ++ list2 ! ! #(concat) list1 -- list2 #(set diff) a in enum #(membership) ^term #(no reassign)
Integer 1234 0xcafe 0177 0b100 10_000 Float 1.0 3.1415 6.02e23 Atom :foo :me@home :"with spaces" Tuple { 1, 2, :ok, "xy" } (like array)
List [ 1, 2, 3 ] (like linked list) [ head | tail ] 'abc' ''' here doc ''' (see Enum and List modules)
Keyword List (can duplicate keys) [ a: "Foo", b: 123 ]
Map (no duplicate keys) %{ key => value, key => value }
Binary << 1, 2 >> or "abc" """ here doc """ "#{interpolated}" << name::prop-prop-prop … >> binary, bits, bitstring, bytes, float, integer, utf8, utf16, utf32, size(n), signed/unsigned, big/little native
Truth true, false, nil
Range a..b
fn parms [guard] -> body parms [guard] -> body end
call with func.()
Shortcut: &(...) &1,&2 as parameters
(Only in modules, records, etc) def name(parms) [guard] do expression end
def name(parms) [guard], do: expr Default params: parameter \ default
defp for private functions Multiple heads with different params and/ or guards allowed. Capture a function with: &mod_name.func_name/arity (Can omit mod_name)
defmodule mod_name do @moduledoc "description" @doc "description" function/macro end
require Module (used for macros)
use Module calls Module.using
import Module [,only:|except:] alias mod_path [, as: Name] alias mod_path.{ Name, Name, Name... } @attribute_name value Call Erlang using: :module.function_name
Part of pattern match when expr
where operators in expr are limited to: ==, !=, ===, !==, >, <, <=, >=, or, and, not, !, +, -, *, /, in, is_atom, is_binary, is_bitstring, is_boolean, is_exception, is_float, is_function, is_integer, is_nil, is_list, is_number, is_pid, is_port, is_reference, is_tuple, abs(num), bit_size(bits), byte_size(bits), div(num,num), elem(tuple, n), float(term), hd(list), length(list), node(), node(pid|ref|port), rem(num,num), round(num), self(), tl(list), trunc(num), tuple_size(tuple) <> and ++ (left side literal)
for generator/filter [, into: value ], do: expr Generators are: pattern <- list With binaries as: for << ch <- "hello" >>, do: expr
something do expr end
something, do: expr
else, rescue, try, ensure also generate keyword args, and are then compiled
if expr do exp else exp end
unless expr do exp else exp end
case expr do match [guard] -> exp match [guard] -> exp … end
cond do bool -> exp bool -> exp end
with match <- exp, match <- exp, …, do: exp
executes all exp until a match fails (and is returned), or the do: is run.
%{ key => value, key => value } value = map[key] (can return nil) value = map.key (if key is atom; can fail) newmap = %{ oldmap | key => newval } or newmap = Map.put(oldmap, key, newval) Map.put_new/3 to add a key
defmacro macroname(parms) do parms are quoted args return quoted code which is inserted at call site end
quote do: … returns internal rep. quote bind_quoted: [name: name] do: ...
unquote do: … only inside quote, injects code fragment without evaluation
MODULE FILE DIR ENV CALLER (macros only)
defprotocol module.name do @moduledoc description @only [list of types] (optional) def name(parms) end defimpl mod.name, for: type do @moduledoc description def name(type, value) do expr end end Allowed types: Any Atom BitString Function List Number PID Port Record Reference
~r{pattern}opts f match beg of ml string g use named groups i case insensitive m ^ and $ match each line in multiline r reluctant (not greedy) s . matches newline u Unicode patterns x ignore whitespace and comments
pid = spawn(anon_function) pid = spawn(mod, func, args) (also spawn_link) receive do { sender, msg, … } -> send sender { :ok, value } after timeout -> ... end
expr |> f1 |> f2(a,b) |> f3(c) (same as) f3(f2(f1(expr), a, b), c)
defmodule Name do defstruct field: default, … end %Name{field: value, field: value, …} new_struct = %{ var | field: new_value }
~type{ content } Delimiter: { }, [ ], ( ), / /, | |, " ", or ' ' ~S string (no interpolation) ~s string (with interpolation) ~C character list (no interpolation) ~c character list (with interpolation) ~R regexp ~r regexp w/interpolation ~W words (white space delim) ~w words w/interpolation
3 # integer 0x1F # integer 3.0 # float
:hello # atom
{1,2,3} # tupla
elem({1, 2, 3}, 0) #=> 1
[1,2,3] # lista
[head | tail] = [1,2,3] head #=> 1 tail #=> [2,3]
<<1,2,3>> # binary
"hello" # string 'hello' # char list
""" Strings de múltiplas linhas. """ #=> "Strings\nde múltiplas\nlinhas"
"héllò" #=> "héllò"
<<?a, ?b, ?c>> #=> "abc" [?a, ?b, ?c] #=> 'abc'
?a #=> 97
[1,2,3] ++ [4,5] #=> [1,2,3,4,5] 'hello ' ++ 'world' #=> 'hello world'
<<1,2,3>> <> <<4,5>> #=> <<1,2,3,4,5>> "hello " <> "world" #=> "hello world"
1..10 #=> 1..10 menor..maior = 1..10 # Pattern matching pode ser usada em ranges também [lower, upper] #=> [1, 10]
1 + 1 #=> 2 10 - 5 #=> 5 5 * 2 #=> 10 10 / 2 #=> 5.0
div(10, 2) #=> 5
rem(10, 3) #=> 1
true and true #=> true false or true #=> true
1 || true #=> 1 false && 1 #=> false nil && 20 #=> nil !true #=> false
1 == 1 #=> true 1 != 1 #=> false 1 < 2 #=> true
1 == 1.0 #=> true 1 === 1.0 #=> false
1 < :hello #=> true
if false do "Isso nunca será visto" else "Isso será" end
unless true do "Isso nunca será visto" else "Isso será" end
case {:um, :dois} do
{:quatro, :cinco} ->
"Isso não corresponde"
{:um, x} ->
"Isso corresponde e vincula x
a :dois
"
_ ->
"Isso corresponde a qualquer valor"
end
[head | _] = [1,2,3] head #=> 1
[head | _tail] = [:a, :b, :c] head #=> :a
cond do 1 + 1 == 3 -> "Nunca serei visto" 2 * 5 == 12 -> "Nem eu" 1 + 2 == 3 -> "Mas eu serei" end
cond do 1 + 1 == 3 -> "Nunca serei visto" 2 * 5 == 12 -> "Nem eu" true -> "Mas eu serei (isso é essencialmente um else)" end
try do throw(:hello) catch message -> "Deu #{mensagem}." after IO.puts("Sou o after.") end #=> Sou o after
square = fn(x) -> x * x end square.(5) #=> 25
f = fn x, y when x > 0 -> x + y x, y -> x * y end
f.(1, 3) #=> 4 f.(-1, 3) #=> -3
is_number(10) #=> true is_list("ola") #=> false elem({1,2,3}, 0) #=> 1
defmodule Math do def sum(a, b) do a + b end
def square(x) do x * x end end
Math.sum(1, 2) #=> 3 Math.square(3) #=> 9
defmodule PrivateMath do def sum(a, b) do do_sum(a, b) end
defp do_sum(a, b) do a + b end end
PrivateMath.sum(1, 2) #=> 3
defmodule Geometry do def area({:rectangle, w, h}) do w * h end
def area({:circle, r}) when is_number(r) do 3.14 * r * r end end
Geometry.area({:rectangle, 2, 3}) #=> 6 Geometry.area({:circle, 3}) #=> 28.25999999999999801048
#=> ** (FunctionClauseError) no function clause matching in Geometry.area/1
defmodule Recursion do def sum_list([head | tail], acc) do sum_list(tail, acc + head) end
def sum_list([], acc) do acc end end
Recursion.sum_list([1,2,3], 0) #=> 6
defmodule MyMod do @moduledoc """ Este é um atributo embutido em um módulo de exemplo. """
@my_data 100 # Este é um atributo customizado. IO.inspect(@my_data) #=> 100 end
defmodule Pessoa do defstruct nome: nil, idade: 0, peso: 0 end
joe_info = %Pessoa{ nome: "Joe", idade: 30, peso: 180 } #=> %Pessoa{idade: 30, peso: 180, nome: "Joe"}
joe_info.name #=> "Joe"
older_joe_info = %{ joe_info | idade: 31 } #=> %Pessoa{idade: 31, peso: 180, nome: "Joe"}
try do raise "algum erro" rescue RuntimeError -> "resgatado um erro em tempo de execução" _error -> "isso resgatará qualquer erro" end
try do raise "algum erro" rescue x in [RuntimeError] -> x.message end
f = fn -> 2 * 2 end #=> #Function<erl_eval.20.80484245> spawn(f) #=> #PID<0.40.0>
defmodule Geometry do def area_loop do receive do {:rectangle, w, h} -> IO.puts("Area = #{w * h}") area_loop() {:circle, r} -> IO.puts("Area = #{3.14 * r * r}") area_loop() end end end
pid = spawn(fn -> Geometry.area_loop() end) #=> #PID<0.40.0>
send pid, {:rectangle, 2, 3} #=> Area = 6
send pid, {:circle, 2} #=> Area = 12.56000000000000049738
self() #=> #PID<0.27.0>