3
2

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.

口で言うより行うことがErlang習得への近道と信じています。

マッチ演算子

=演算子は代数学でいうところの等号に相当するものです。左辺と右辺の値をマッチさせ、マッチに成功すると、式の値が返されます。失敗する場合はエラーを投げます。

まずは単純なマッチングを試してみます。

> X = 1.
1

> 1 = X.
1

> 2 = X.
** exception error: no match of right hand side value 1

リストでマッチングを試してみます。

> L1 = [1, 2, 3].
[1,2,3]

> [1, 2, 3] = L1.
[1,2,3]

> [] = L1.
** exception error: no match of right hand side value [1,2,3]

> [1 | Tail] = L1.
[1, 2, 3]

> Tail.
[2, 3]

> [2|_] = L1.
** exception error: no match of right hand side value [1,2,3]

タプルでマッチングを試してみます。

> {ok, Value} = {ok, "Successful!"}.
{ok,"Successful!"}

> Value.
"Successful!"

> {ok, Value} = {error}.
** exception error: no match of right hand side value {error}

マップでマッチングを試してみます。

> #{y := Y} = #{x => 1, y => 2}.
#{x => 1,y => 2}

> Y
2

束縛

Erlangでは一度変数が束縛されると、値の変更はできません。

> Z = 1.
1

> Z = 2.
** exception error: no match of right hand side value 2

関数

Erlangではパターンマッチは変数だけに限定されているわけではなく、関数へと適用することもできます。

最初にマッチするオプションが実行されます。

> F = fun (ok) -> a; (error) -> b; (_) -> c end.
#Fun<erl_eval.42.3316493>

> F(ok).
a

> F(error).
b

> F(hello).
c

Elixirにも挑戦したい

闘魂ElixirシリーズとElixir Schoolがオススメです。

3
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?