1、if語句 , F#返回值不需要顯式的寫出返回類型,在寫if等流程控制時,要控制好返回值信息,如if 語句塊和 else 語句塊的返回值類型要匹配;不能出現if有返回、else無返回;也不能只出現一個單條件返回,如只出現一個if語句並且有返回值信息,而沒有else語句,這樣在不滿足if 情況時則可能不會有返回值。
let fun1 x = //定義一個返回字符串的方法fun1
if x > 10 then "輸入的值大於10" //當x > 10 返回大於10的信息
else "輸入的值小於等於10" //相反返回小於等於10 ,因爲有返回值 else語句塊不能缺失 ,否則可能出現滿足if條件有返回,不滿足無返回的情況
printfn "%s" (fun1 10)
let num1 = //定義一個無參的方法num1 ,返回類型爲整型
let x = 10
if x > 10 then
10
else
x
printfn "%i" num1
let outPutNum x = //定義一個無返回值的方法
if x >= 10 then printfn "%i" 10
else printfn "%i" x
outPutNum 10
let outPutNum2 x = //定義一個無返回值的方法
if x >= 10 then printfn "%i" 10
outPutNum2 10
let checkNum x = //定義一個無返回值的方法,判斷輸入參數值是否等於10
if x = 10 then printfn "%s" "x的值和10相等" //(注意判斷相等是單等於號)
else printfn "%s" "x的值和10不相等"
checkNum 10
2、類型約束(或類型註釋) 將參數 或 標識符用括號括起來,在後面用: type的方式來聲明具體的數據類型
let ( x : int ) = 1 // 申明整形標識符x
let hello ( name : string ) = //hello 方法的參數name是string類型
printfn "hello %s" name
let ( names : list<string>) = ["a";"b";"c";"d"]
let add (x : int) (y : int) = x + y
3、模式匹配 match 類似於 C# switch語句
let rec luc x =
match x with
| x when x <= 0 -> failwith "value must be greater than 0"
| 1 -> 1
| 2 -> 3
| x -> luc (x - 1) + luc ( x-1 - 2)
let printout x =
match x with
| x -> printf "%s" x
printout "a"
let getLanguage ( lId : int ) =
match lId with
| 1 -> "普通話"
| 2 -> "English"
| lId when lId <= 0 -> failwith "出錯啦"
| lId -> "未知"
printfn "%s" (getLanguage -3)
let getMonthDays x = //當多個匹配項的結果都是一樣的時候,可以連續用|來間隔多個 case情況 ,_ 類似sql的通配符表示其它匹配值情況
match x with
| 1 | 3 | 5 | 6 | 8 | 10 | 12 -> 31
| 4 | 7 | 9 | 11 -> 30
| 2 -> 28
| _ -> failwith "月份不正確" //x _都可以匹配
printfn "%i" (getMonthDays 2)
printfn "%i" (getMonthDays 5)
printfn "%i" (getMonthDays 7)
let getMonthDays2 m y =
let checkRun year =
(year % 4 = 0 || year % 100 = 0)&&( year % 400 <> 0)
match m with
| 1 | 3 | 5 | 6 | 8 | 10 | 12 -> 31
| 4 | 7 | 9 | 11 -> 30
| 2 when (checkRun y) = true -> 29
| 2 when (checkRun y) = false -> 28
| _ -> failwith "月份不正確" //x _都可以匹配
printfn "%i" (getMonthDays2 13 2000)
4、List和pattern match (列表和模式匹配) , 列表在進行模式匹配時可以用head 和 tail來表示列表頭和列尾,理解時可以把列表看成是鏈表 head 表示頭結點,tail表示除了頭結點外的尾鏈s//如 [ 1 ; 2 ; 3 ; 4 ] head 是 1 , tail 是 [ 2 ; 3; 4 ] , 如 [ 1 ] head 是 1 , tail 是 [ ]
let outputListHead l =
match l with
| head :: tail -> printfn "%A" head //在匹配時,case 應該是個list,head::tail,head與tail連接成爲list, (::連接符參考list元素與list連接返回新列表, @用來連接兩個列表)
outputListHead [1;2;3;4] //輸出 1
let rec outPutList (l : List<int>) = //遞歸輸出列表中的元素,輸出列表等於輸出列表頭再輸出尾列表
match l with
| head :: tail -> printfn "%A" head ; outPutList tail ;
| [] -> printfn "%s" "結束";
outPutList [ for i in 1..2..9 -> i ]