Fsharp: if then (conditional)

By Xah Lee. Date: . Last updated: .

If then else

the true and false branches must agree on type.

printfn "%s" (if 3 = 4 then "yes" else "no" )
// no
let x = -3
let y = if x < 0 then 3 else 4

printfn "%A" y
// 3
// a function
let abs x =
    if x < 0 then -x else x

printfn "%A" (abs -5)
// 5

Elif (else tail chain)

elif is short for else if

let x = 3
let y = 4
printfn "%s" (if x = y then "is equal" elif x < y then "is less than" else "is greater than")
// is less than

If then

the then branch must return a unit type.

(if 3 = 3 then printfn "yes" )
// yes

Reference