Erlang - 多表達式



if 表示式也允許同時評估多個表示式。Erlang 中此語句的通用形式如下程式所示:

語法

if
condition1 ->
   statement#1;
condition2 ->
   statement#2;
conditionN ->
   statement#N;
true ->
   defaultstatement
end.

在 Erlang 中,條件是一個表示式,它計算結果為真或假。如果條件為真,則執行 statement#1。否則,評估下一個條件,依此類推。如果沒有評估結果為,則評估defaultstatement

下圖是上述語句的一般示意圖。

Multiple Expression

以下程式是 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 後面。

  • -> 運算子需要跟在真表示式後面。

  • 需要使用語句“end”來表示 if 塊的結束。

上述程式的輸出將為:

輸出

A is less than B
erlang_decision_making.htm
廣告
© . All rights reserved.