Erlang多運算式

if運算式也允許進行一次評估(計算)多個運算式。在 Erlang 這個語句的一般形式顯示在下面的程式 -

語法

if
condition1 ->
   statement#1;
condition2 ->
   statement#2;
conditionN ->
   statement#N;
true ->
   defaultstatement
end.
在 Erlang 中,條件是計算結果為真或假的運算式。如果條件為真,則 statement#1 會被執行。否則評估(計算)下一個條件運算式等等。如果沒有一個運算式的計算結果為真,那麼 defaultstatement 評估(計算)。
下圖是上面給出的語句的一般流程示意圖:
Erlang多運算式
下麵的程式是在 Erlang 中一個簡單的 if 運算式的例子 -

示例

-module(helloworld).
-export([start/0]).

start() ->
   A = 5,
   B = 6,
   if
      A == B ->
         io:fwrite("A is equal to B");
      A < B ->
         io:fwrite("A is less than B");
      true ->
         io:fwrite("False")
   end.
以下是上述程式需要說明的一些關鍵點 -
  • 這裏所使用的運算式是變數A和B的比較
  • -> 運算符需要在運算式之後
  • 符號 ";" 需要在 statement#1 語句之後

  • -> 運算符需要在 true 運算式之後

  • 語句 “end” 需要用來表示 if 塊的結束
上面的代碼的輸出結果是 -
A is less than B

上一篇: Erlang if語句 下一篇: Erlang內嵌if語句