本文概述
- F#创建可识别联合示例
- F#可识别联合示例
type type-name =
| case-identifier1 [of [ fieldname1 : ] type1 [ * [ fieldname2 : ] type2 ...]
| case-identifier2 [of [fieldname3 : ]type3 [ * [ fieldname4 : ]type4 ...]
...
F#创建可识别联合示例
type Calculate =
| Add of val1 : float * val2 : float
| Square of val1 : int
在上面的代码中, 我们有两种情况的矩形和圆形, 每种情况都有不同的字段集。现在让我们看看如何为这些情况调用和设置值。
let add = Add(val1 = 1.3, val2 = 10.0)
let square = Square (1)
它允许你在调用时使用字段名, 也可以像在Square案例代码中那样传递值。如果使用字段名称, 则无需维护字段顺序。仅传递值时, 必须在传递值之前确保字段顺序。
F#可识别联合示例
type Calcualte =
| Add of val1 : int * val2 : int
| Subtract of val1 : int * val2 :int
| Multiply of val1 : int * val2 : intlet compute vall =
match vall with
| Add (val1, val2) ->
val1+val2
| Subtract (val1, val2)->
val1-val2
| Multiply (val1, val2)->
val1*val2let addition = compute (Add(10, 10))
let subtraction = compute (Subtract(20, 10))
let multiplication = compute (Multiply(2, 5))printf "Addition = %d\nSubtraction = %d\nMultiplication = %d" addition subtraction multiplication
【F#可识别联合】输出:
Addition = 20
Subtraction = 10
Multiplication = 10