軌道
/
Elixir
Elixir
/
課程大綱
/
模式配對
模式

模式配對 在 Elixir

73 個練習

關於 模式配對

在撰寫 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
    
透過 GitHub 編輯 連結會在新視窗或分頁中開啟

學習 模式配對

練習已鎖定

再解鎖 10 個練習,就能練習 模式配對