15
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?

More than 1 year has passed since last update.

今日のElixirSchoolメモ4「パターンマッチ」

Posted at

パターンマッチはElixirの強力な部品で、単純な値やデータ構造、果ては関数でさえもマッチすることができます。

=演算子

Elixirでは、 = 演算子は実際には代数学での等号に値するマッチ演算子。
マッチ演算子を通して値を代入し、その後マッチさせることができる。
Elixirは左辺の変数の値しか変更しない。

iex(37)> x = 1
1
iex(38)> 1 = x
1
iex(39)> 2 = x
** (MatchError) no match of right hand side value: 1
iex(39)> x = 3
3

タプルのマッチング

タプルのマッチング

iex(57)> {:ok, value} = {:ok, "Successful!"}
{:ok, "Successful!"}
iex(58)> value
"Successful!"
iex(59)> {:ok, value} = {:ok, "Konchiwa"}
{:ok, "Konchiwa"}
iex(60)> value
"Konchiwa"
iex(61)> {:ok, value} = {:error, "Konchiwa"}
** (MatchError) no match of right hand side value: {:error, "Konchiwa"}

Elixirは左辺の値と右辺の値を同じにする方法を探す。
左辺は3つの変数を持つリスト、右辺は3つの値からなるリスト。そのため変数それぞれに対応する値をセットすれば、両方同じにできる。

iex(41)> list = [1, 2, 3]
[1, 2, 3]
iex(42)> [a, b, c] = list
[1, 2, 3]
iex(43)> a
1
iex(44)> b
2
iex(45)> c
3

_(アンダースコア)

_(アンダースコア)で値を無視することができる。
これは変数のように振る舞うが、セットされた値を即座に捨ててしまう。

iex(46)> list = [1, 2, 3]
[1, 2, 3]
iex(47)> [a, 1, b] = list
** (MatchError) no match of right hand side value: [1, 2, 3]

iex(47)> [a, _, b] = list
[1, 2, 3]

ピン演算子(^)

ピン演算子(^)は変数を固定することができる。
マッチ演算子は左辺に変数がある場合、代入操作を行い、変数を再び束縛するが、それが望ましくない場合に用いる。

iex(48)> x = 1
1
iex(49)> ^x = 2
** (MatchError) no match of right hand side value: 2

iex(49)> {x, ^x} = {2, 1}
{2, 1}
iex(50)> x

関数の節でのピン演算子

iex(62)> greeting = "Hello"
"Hello"
iex(63)> greet = fn
...(63)> (^greeting, name) -> "Hi #{name}"
...(63)> (greeting, name) -> "#{greeting}, #{name}"
...(63)> end
#Function<41.3316493/2 in :erl_eval.expr/6>
iex(64)> greet.("Hello", "Sean")
"Hi Sean"
iex(65)> greet.("Mornin'", "Sean")
"Mornin', Sean"
iex(66)> greet.("Evening'", "Sean")
"Evening', Sean"
iex(67)> greet.("Hello", "Sean")
"Hi Sean"
iex(68)> greeting
"Hello"
15
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
15
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?