Skip to content

F# 速查表

.NET 平台上的函数优先编程语言。

01

快速上手

Hello World

printfn 是标准的打印函数。

fsharp
printfn "Hello, World!"

let 绑定

let 不可变;可变值用 mutable + <-。

fsharp
let x = 10
let mutable y = 20
y <- 25

函数

函数默认柯里化。

fsharp
let add a b = a + b
let result = add 3 4

// Explicit types
let divide (a: float) (b: float) : float = a / b

管道运算符

|> 从左向右传值,在 F# 中极为常用。

fsharp
[1; 2; 3; 4; 5]
|> List.filter (fun x -> x % 2 = 0)
|> List.map (fun x -> x * 2)
|> List.sum
02

类型

记录

用 'with' 对记录做不可变更新。

fsharp
type Person = { Name: string; Age: int }
let p = { Name = "Alice"; Age = 30 }
let p2 = { p with Age = 31 }

可辨识联合(DU)

DU 是和类型;用 match 做穷尽处理。

fsharp
type Shape =
  | Circle of radius: float
  | Rectangle of w: float * h: float

let area s =
  match s with
  | Circle r -> 3.14 * r * r
  | Rectangle (w, h) -> w * h

Option

Option<T> = Some T | None,保证空值安全。

fsharp
let safeDiv a b =
  if b = 0 then None else Some (a / b)

match safeDiv 10 2 with
| Some v -> printfn "%d" v
| None -> printfn "error"
03

集合

列表

List 模块提供标准函数式操作。

fsharp
let xs = [1; 2; 3; 4; 5]
List.map (fun x -> x * 2) xs
List.filter (fun x -> x > 2) xs
List.fold (+) 0 xs

数组

数组可变;用 .[] 索引。

fsharp
let arr = [|1; 2; 3|]
arr.[0] <- 10

序列

seq 是惰性求值的,类似 IEnumerable。

fsharp
seq { 1..10 }
seq { for i in 1..10 do if i % 2 = 0 then yield i }

这篇内容对您有帮助吗?