2
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習得への近道と信じています。

ガード節

ガード節を用いて、パターン内の変数に対して簡単なテストや比較を行うことができます。

練習してみます。

以下の例では引数の数字を比較してどう処理すべきかを決定します。この無名関数をErlangシェルに貼り付けてみてください。

PN = fun 
  (Number) when Number > 0 -> 
    positive; 
  (Number) when Number < 0 -> 
    negative;
  (Number) ->
    zero
end.

引数のパターンに応じて処理を切り替えることができました。

> PN(0).
zero

> PN(1).
positive

> PN(-1).
negative

以下の例では引数の型に基づいてどう処理すべきかを決定します。この無名関数をErlangシェルに貼り付けてみてください。

CheckType = fun 
  (X) when is_list(X) -> 
    io:format("~pはリストです。~n", [X]); 
  (X) when is_tuple(X) -> 
    io:format("~pはタプルです。~n", [X]); 
  (X) ->
    io:format("~pはタプルでもリストでもありません。~n", [X])
end.

引数の型に応じて処理を切り替えることができました。

> CheckType([]).
[]はリストです。
ok

> CheckType({}).
{}はタプルです。
ok

> CheckType(#{}).
#{}はタプルでもリストでもありません。
ok

Erlangのビルトイン関数(BIFs)にガードとして使える便利な関数がいくつかあります。

Elixirにも挑戦したい

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

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