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

if式の書き方

if
  条件1 ->
    本文1;
  条件N ->
    本文N
end
  1. trueと評価される条件が見つかるまで順次走査される
  2. 一つの条件もtrueと評価されない場合には、if_clause実行時エラーが発生する
  3. trueと評価された条件に対応する本文(,で区切られた一連の式)が評価される
  4. 本文の戻り値が、if式の戻り値となる

他のプログラミング言語でいう「else」に相当する記述をしたい場合は、最後の条件でtrueを使うことができますが、可読性を考えて可能であれば条件を明示することが推奨されているようです。

試しに練習目的でif式を使った簡単な無名関数を書いてみます。2つの値を比較した結果を印字するだけの関数です。無名関数なので、Erlangシェルに貼り付けて使えます。

CompareNumbers = fun (A, B) ->
  if
    A > B ->
      io:format("~p is greater than ~p~n", [A, B]);
    A < B ->
      io:format("~p is less than ~p~n", [A, B]);
    true ->
      io:format("~p is equal to ~p~n", [A, B])
  end
end.
> CompareNumbers(1, 2).
1 is less than 2
ok

> CompareNumbers(2, 1).
2 is greater than 1
ok

> CompareNumbers(1, 1).
1 is equal to 1
ok

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?