在撰寫 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