条件分岐
条件分岐
if 条件 then 式 else 式
- 条件はbool型
- then,elseの式は同じ型の持つ必要がある
#if 2 < 1 then 3 else 4 ;; - : int = 4 #if "true" = then 3.14 else 2.72 ;; Error: This expression has type string but is here used with type bool #if "a" = "b" then true else false ;; - : bool = false #if true < false then 1 else "2" ;; Error: This expression has type string but is here used with type int #if not (3 = 4) then 1 < 2 else 1 > 2 ;; - : bool = true
こうゆう風な書き方も出来る。
let func x = base + x * (if x < 30 then 1 else 2)
条件分岐の作り方
- どのような場合分けが必要か。例を作ってテストプログラムとする。
- 本体の前に条件を考える。この時点ではthen,elseの式は適当な値をいれておいて動作確認。
- 大枠が完成したら、then,else部分の式を作成してテスト
与えられた引数の絶対値を返す関数
(* xの絶対値を返す *) (* abs_value : float -> float *) let abs_value x = if x < 0. then -. x else x (* test *) let test1 = abs_value 5.0 = 5.0 let test2 = abs_value (-2.5) = 2.5
ここで、test2に若干はまる
# abs_value -2.5 ;; Error: This expression has type float -> float but is here used with type int
こう書くと
abs_value - 2.5
と解釈されてしまうようです。
ので
# abs_value (-2.5) ;; - : float = 2.5
とする必要があります。
else ifを書きたい場合は
let temper t = if t < 15 then "usual" else if t <= 25 then "comfortable" else "hot"
みたいになる。