什么是 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# 教程