F# - 联合(Unions)

F# - 联合(Unions) 首页 / F#入门教程 / F# - 联合(Unions)

联合(Unions)或有区别的联合(Discriminated Unions)使您可以创建明确的选择集的复杂数据结构。如,您需要构建 choice 变量的实现,该变量具有两个值yes和no,使用联合(Unions)工具,可以对此进行设计。

type type-name =
   | case-identifier1 [of [ fieldname1 : ] type1 [ * [ fieldname2 : ] 
type2 ...]
   | case-identifier2 [of [fieldname3 : ]type3 [ * [ fieldname4 : ]type4 ...]
...

简单实现如下所示-

type choice =
   | Yes
   | No

以下示例使用类型选择-

链接:https://www.learnfk.comhttps://www.learnfk.com/fsharp/fsharp-discriminated-unions.html

来源:LearnFk无涯教程网

type choice =
   | Yes
   | No

let x=Yes (* creates an instance of choice *)
let y=No (* creates another instance of choice *)
let main() =
   printfn "x: %A" x
   printfn "y: %A" y
main()

编译并执行程序时,将产生以下输出-

无涯教程网

x: Yes
y: No

示例1

以下示例显示了将状态设置为高(High)或低(Low)的电压状态的实现-

type VoltageState =
   | High
   | Low

let toggleSwitch=function (* pattern matching input *)
   | High -> Low
   | Low -> High

let main() =
   let on=High
   let off=Low
   let change=toggleSwitch off

   printfn "Switch on state: %A" on
   printfn "Switch off state: %A" off
   printfn "Toggle off: %A" change
   printfn "Toggle the Changed state: %A" (toggleSwitch change)

main()

编译并执行程序时,将产生以下输出-

无涯教程网

Switch on state: High
Switch off state: Low
Toggle off: High
Toggle the Changed state: Low

示例2

type Shape =
   //这里存储一个圆的半径
   | Circle of float

   //这里存储边长。
   | Square of float

   //这里存储高度和宽度。
   | Rectangle of float * float

let pi=3.141592654

let area myShape =
   match myShape with
   | Circle radius -> pi * radius * radius
   | Square s -> s * s
   | Rectangle (h, w) -> h * w

let radius=12.0
let myCircle=Circle(radius)
printfn "Area of circle with radius %g: %g" radius (area myCircle)

let side=15.0
let mySquare=Square(side)
printfn "Area of square that has side %g: %g" side (area mySquare)

let height, width=5.0, 8.0
let myRectangle=Rectangle(height, width)
printfn "Area of rectangle with height %g and width %g is %g" height width (area myRectangle)

编译并执行程序时,将产生以下输出-

无涯教程网

Area of circle with radius 12: 452.389
Area of square that has side 15: 225
Area of rectangle with height 5 and width 8 is 40

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

技术与商业案例解读 -〔徐飞〕

左耳听风 -〔陈皓〕

从0开始学架构 -〔李运华〕

10x程序员工作法 -〔郑晔〕

Elasticsearch核心技术与实战 -〔阮一鸣〕

.NET Core开发实战 -〔肖伟宇〕

To B市场品牌实战课 -〔曹林〕

Web 3.0入局攻略 -〔郭大治〕

AI 应用实战课 -〔黄佳〕

好记忆不如烂笔头。留下您的足迹吧 :)