Using ExUnit: mix test --stale --max-failures 1 --listen-on-stdin --trace --seed 0
String
Integer
Float
Boolean
Atom (like a “Symbol” in js, value is itself)
Bitstring (just sequence of bits) > Binary (Bitstring % 8 === 0) > Strings (UTF-8 Binary)
Tuples: {"any", "type", 1, false}
List: ["here", "too", 123, true]
Charlist: ['a', 'b', 'c'] = 'abc'
Maps: %{"any" => :value, 123 => true, "keys" => :too}
%{a: 1, b: 2} = %{:a => 1, :b => 2}
and map.a = 1
map[key]
; nil
on invalid key; useful for dynamically created mapsmap.key
when key is atom; error on invalid key; useful for static maps%{map | existing_key: new_value }
Map.put(map, key, value)
Keywords: ?
Structs: ?
if: if condition do \n ... \n end
or if condition, do: ..., else: ...
unless: opposite of if
, same syntax
case: case variable do \n pattern -> return \n ... \n end
cond: cond do \n condition -> return \n ... \n end
with: with pattern do \n ... \n end
or with pattern, do: ...
Boolean Operators: and/&& or/|| not/!
Exists: var in list, e.g, 1 in [1, 2, 3, 4]
= true, can be used as not in
Anonymous: sum = fn a, b -> a + b end
called as sum.(1, 2)
= 3
Shorthand: sum = &(&1 + &2)
same as above
Parameters can be pattern matched to return different results:
sum -> fn \n pattern -> return \n pattern -> return \n end
Like Classes
Functions inside modules are defined using def
keyword, defp
for private
constants: @name value
(parameters) structs: defstruct [:var1, :var2]
Create new type and assign it to spec:
@type address_map() :: %{street: String.t(), postal_code: String.t(), city: String.t()}
@type address_tuple() :: {street :: String.t(), postal_code :: String.t(), city :: String.t()}
@type address() :: address_map() | address_tuple()
@doc """
Formats the address as an uppercase multiline string.
"""
@spec format_address(address()) :: String.t()
def format_address(%{street: street, postal_code: postal_code, city: city}) do
format_address({street, postal_code, city})
end
def format_address({street, postal_code, city}) do
"""
#{String.upcase(street)}
#{String.upcase(postal_code)} #{String.upcase(city)}
"""
end
List of types: Typespecs