F# 是通用程式設計語言,用於撰寫簡潔、強固且高效能的程式代碼。
F# 可讓您撰寫簡潔、自我說明的程式碼,讓您專注於問題領域,而非程式設計的細節。
它會這樣做,而不會損害速度和相容性 - 它是開放原始碼、跨平臺且互通的。
open System // Gets access to functionality in System namespace.
// Defines a list of names
let names = [ "Peter"; "Julia"; "Xi" ]
// Defines a function that takes a name and produces a greeting.
let getGreeting name = $"Hello, {name}"
// Prints a greeting for each name!
names
|> List.map getGreeting
|> List.iter (fun greeting -> printfn $"{greeting}! Enjoy your F#")
F# 有許多功能,包括:
- 輕量語法
- 預設為不可變
- 類型推斷和自動一般化
- 第一類函式
- 功能強大的數據類型
- 模式比對
- 異步程序設計
F # 語言指南記載了一組完整的功能。
豐富數據類型
// Group data with Records
type SuccessfulWithdrawal =
{ Amount: decimal
Balance: decimal }
type FailedWithdrawal =
{ Amount: decimal
Balance: decimal
IsOverdraft: bool }
// Use discriminated unions to represent data of 1 or more forms
type WithdrawalResult =
| Success of SuccessfulWithdrawal
| InsufficientFunds of FailedWithdrawal
| CardExpired of System.DateTime
| UndisclosedFailure
F# 記錄和區分聯合預設為非空、不可變且可比較,這使得它們非常容易使用。
函式和模式比對的正確性
F# 函式很容易定義。 結合 模式比對時,它們可讓您定義編譯程式強制執行其正確性的行為。
// Returns a WithdrawalResult
let withdrawMoney amount = // Implementation elided
let handleWithdrawal amount =
let w = withdrawMoney amount
// The F# compiler enforces accounting for each case!
match w with
| Success s -> printfn $"Successfully withdrew %f{s.Amount}"
| InsufficientFunds f -> printfn $"Failed: balance is %f{f.Balance}"
| CardExpired d -> printfn $"Failed: card expired on {d}"
| UndisclosedFailure -> printfn "Failed: unknown :("
F# 函式也是第一級函式,這表示它們可以當做參數傳遞,並從其他函式傳回。
定義物件作業的函式
F# 完全支援 物件,當您需要混合數據和功能時,這非常有用。 F# 成員和函式可以被定義來操作物件。
type Set<'T when 'T: comparison>(elements: seq<'T>) =
member s.IsEmpty = // Implementation elided
member s.Contains (value) =// Implementation elided
member s.Add (value) = // Implementation elided
// ...
// Further Implementation elided
// ...
interface IEnumerable<'T>
interface IReadOnlyCollection<'T>
module Set =
let isEmpty (set: Set<'T>) = set.IsEmpty
let contains element (set: Set<'T>) = set.Contains(element)
let add value (set: Set<'T>) = set.Add(value)
在 F# 中,您通常會撰寫程式碼,將物件視為函式運算的一種型別。 在較大的 F# 程式中,常見的功能,例如泛型介面、物件表示式以及明智地使用成員。
後續步驟
若要深入瞭解一組較大的 F# 功能,請參閱 F# 導覽。