什麼是 F#

F# 是通用程式設計語言,可用於撰寫簡潔、強固且高效能的程式碼。

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# 記錄和區別聯集預設為非 null、不可變且可比較的類型,所以很方便使用。

函式和模式比對的正確性

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# 導覽