F#在线运行

版本:

所属目录
点击了解高性能代码运行API
运行结果
教程手册
代码仓库
极速运行
终端运行
图形+终端

                        
以下是用户最新保存的代码
函数式 赛车模拟 (自由格式) 发布于:2021-02-02 10:52 转换OCaml对象模式 发布于:2021-02-01 00:46 [更多]
显示目录

差别联合



学习嵌入式的绝佳套件,esp8266开源小电视成品,比自己去买开发板+屏幕还要便宜,省去了焊接不当搞坏的风险。 蜂鸣版+触控升级仅36元,更强的硬件、价格全网最低。

点击购买 固件广场

差别联合

联合(Unions)或差别联合(discriminated unions)允许您构建表示明确定义的一组选择的复杂数据结构。 例如,您需要构建一个achoicevariable的实现,它具有两个值yes和no。 使用Unions工具,你可以自由设计它。

语法

差别联合使用下面的语法定义

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

简单的实现,选择,示例如下

type choice =
   | Yes
   | No

下面的示例使用类型选择

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

以下示例显示了在高电平或低电平时置位的电压状态的实现

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 =
   // here we store the radius of a circle
   | Circle of float

   // here we store the side length.
   | Square of float

   // here we store the height and width.
   | 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
由JSRUN为你提供的F#在线运行、在线编译工具
        JSRUN提供的F# 在线运行,F# 在线运行工具,基于linux操作系统环境提供线上编译和线上运行,具有运行快速,运行结果与常用开发、生产环境保持一致的特点。
yout