3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

elixir 複雑なマッチ

Last updated at Posted at 2024-12-18

パターンマッチ

iex> list = [1, 2, 3]
[1, 2, 3]

[a, b, c] = list
[1, 2, 3]

Elixirは、左辺の値と右辺の値を同じにする方法を探す。左辺は三つの変数を含むリスト、右辺は三つの値からなるリストだ。そのため、変数それぞれに対応する値をセットすれば、両辺を同じにできる。
この処理をパターンマッチという。

※プログラミングElixir 第2販 P.17より抜粋

つまりあるリストに対して対応する値をそれぞれ入れることと説明できる。

image.png

さらにリストを見ていく
以下は失敗パターン

iex(11)> list = [1, 2, 3]
[1, 2, 3]
iex(12)> [a, 1, b] = list
** (MatchError) no match of right hand side value: [1, 2, 3]
    (stdlib 6.1.2) erl_eval.erl:652: :erl_eval.expr/6
    iex:12: (file)

これはiex(11)でlistに1, 2, 3を入れたにもかかわらず次のiex(12)で[a, 1, b]と照らし合わせたためである
a = 1
1 = 2
b = 3
となってしまい2つ目の1 = 2が不正なためマッチエラーが出力された。

参考文献
プログラミングElixir 第2版

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?