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# 教程。