Elm - 決策
決策結構要求程式設計師指定一個或多個條件,由程式進行評估或測試,以及如果條件被確定為真則執行的語句,以及可選地,如果條件被確定為假則執行的其他語句。
下面顯示的是大多數程式語言中常見的典型決策結構的通用形式。
決策結構在執行指令之前會評估條件。Elm 中的決策結構分類如下:
| 序號 | 語句 | 描述 |
|---|---|---|
| 1 | if...then...else 語句 | if 語句由一個布林表示式後跟 then 組成,如果表示式返回 true,則執行 then 部分;如果表示式返回 false,則執行 else 部分。 |
| 2 | 巢狀 if 語句 | 你可以在另一個 if 內部使用一個 if...then...else。 |
| 3 | case 語句 | 測試變數的值是否與一系列值匹配。 |
if...then...else 語句
if…then 結構在執行程式碼塊之前會評估條件。如果布林表示式計算結果為真,則將執行 then 語句內的程式碼塊。如果布林表示式計算結果為假,則將執行 else 語句內的程式碼塊。
與其他程式語言不同,在 Elm 中,我們必須提供 else 分支。否則,Elm 將丟擲錯誤。
語法
if boolean_expression then statement1_ifTrue else statement2_ifFalse
示例
在 REPL 終端中嘗試以下示例。
> if 10>5 then "10 is bigger" else "10 is small" "10 is bigger" : String
巢狀 if
巢狀 if 語句用於測試多個條件。巢狀 if 語句的語法如下:
if boolean_expression1 then statement1_ifTrue else if boolean_expression2 then statement2_ifTrue else statement3_ifFalse
示例
在 Elm REPL 中嘗試以下示例:
> score=80 80 : number > if score>=80 then "Outstanding" else if score > = 70 then "good" else "average" "Outstanding" : String
case 語句
case 語句可以用來簡化 if then else 語句。case 語句的語法如下:
case variable_name of constant1 -> Return_some_value constant2 -> Return_some_value _ -> Return_some_value if none of the above values match
case 語句檢查變數的值是否與預定義的一組常量匹配,並返回相應的值。請注意,每個 case 返回的值必須是相同型別。如果變數的值與任何給定的常量都不匹配,則控制權將傳遞給 *default*(用 //_ 表示),並返回相應的值。
示例
在 Elm REPL 中嘗試以下示例:
> n = 10 10 : number > case n of \ | 0 -> "n is Zero" \ | _ -> "n is not Zero" "n is not Zero" : String
上面的程式碼片段檢查 n 的值是否為零。控制權傳遞給 default,它返回字串“n is not Zero”。
廣告