x = Map.put(%{a:1, b:2}, :c, 3) # (1) add/update an element
x = %{x | c:3} # (2) update an element (syntactic sugar)
y = Map.take(x, [:a, :b]) # (3) take a subset
Python
x = {**{"a": 1, "b": 2}, "c": 3} # (1) and (2)
y = {k: x[k] for k in x if k in ["a", "b"]} # (3)
{a, b, _} = {1, 2, 3} # (1) a = 1, b = 2, don't care about third elem.
[a, ^b] = [1, 2] # (2) a = 1 if second element == value of b (pin)
[head | tail] = [1, 2, 3] # (3) head = 1, tail = [2, 3]
%{a: a} = %{a:1, b:2} # (4) a = 1 (~ destructuring)
with {:ok, string} <- Map.fetch(map, :key),
{value, _} <- Integer.parse(string) do
value
else # first failed match is sent here
mismatch -> mismatch
end
defadd(x, y) do# (1) named function
x + y # last expression is the return valueenddefadd(x, y), do: x + y # (2) shorthand, same as (1)defpadd(x, y), do: x + y # (3) private function
Python
defadd(x, y):# (1) and (2)return x + y
def_add(x, y):# (3)return x + y
# function definition can be splitted in branchesdefop(:add, x, y), do: x + y
defop(:sub, x, y), do: x - y
defop(name, _, _), do: raise "Unknown operation #{name}"
Python
defop(name, x, y):if name == "add":
return x + y
if name == "sub":
return x - y
raise Exception(f"Unknown operation {name}")
# named parameters are (often) passed as keywords
String.split("a,b,c", ",", [{:parts, 2}]) # (1)
String.split("a,b,c", ",", parts:2) # (2) same as (1) syntactic sugar