Elixirの関数を書くときは、パターンマッチングを使った断定的なスタイルを活用できます。
def read_file() do
{:ok, contents} = File.read("hello.txt")
contents
end
パターンマッチングは、マッチ演算子=/2を使って明示的に行います。
演算子の左辺にあるデータの_形_が右辺と一致すると、マッチは成功します。
マッチが成功すると、左辺の変数に右辺の値が束縛されます。
アンダースコア_を使うと、その位置の値を無視できます。
{:ok, number, _} = {:ok, 5, [4.5, 6.3]}
number
# => 5 is bound to this variable
ピン演算子^を使うと、変数の再束縛を防ぎ、代わりに既存の値に対してパターンマッチングできます。
number = 10
{:ok, ^number, _} = {:ok, 5, [4.5, 6.3]}
# => ** (MatchError) no match of right hand side value: {:ok, 5, [4.5, 6.3]}
パターンマッチは関数の節のヘッドでも行えるので、パターンに一致する引数だけがその関数を呼び出します。
関数の節のパターンマッチでも変数を束縛できます。
defmodule Example do
def named_function(:a = atom_variable) do
{atom_variable, 1}
end
end
Example.named_function(:a)
# => {:a, 1}
# The first function clause matches, so it is invoked
Example.named_function(:b)
# => ** (FunctionClauseError) no function clause matching in Example.named_function/1