F#教程: if语句


上回我们利用for进行了循环处理。这次我们学习if语句。简单实例如下:

#light
let add x y = x + y 
if add 2 3 = 5 then printfn "2 + 3 = 5"
if add 2 3 = 6 then printfn "2 + 3 = 6" else printfn "2 + 3 != 6"

  比较的时候仅仅用单个=,而不是通常习惯的==。除此之外,应该都是很普遍的。下一个例子是:

let even = if 10 % 2 = 0 then true else false 
printfn "%A" even

  这里需要注意的是if语句带有值。动作时感觉同C#的三目运算符很类似。

  本例中,if语句的值作为even变量的初始值。带有值的if语句不能这样写:

  let ten = if add a b < 10 then 10

  原因是:else分支没有值,是unit类型,这样就和then分支的类型不一致,所以会有编译错误。

  当然也可以使用else if。

let lang = "VB" 
if lang = "C#" then 
    printfn "This is C#" 
else if lang = "F#" then 
    printfn "This is F#" 
else 
    printfn "Other"

  顺便说下,elif关键字可以用来替代 else if使用。

if lang = "C#" then 
    printfn "This is C#" 
elif lang = "F#" then 
    printfn "This is F#" 
else 
    printfn "Other"

  还可以使用&&和||:

let aa = 1 
let bb = 2 
if aa = 1 && bb = 2 then printfn "Both are true" 
if aa = 2 || bb = 2 then printfn "Either is true"


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3