Chapter3 - Defining Types - Union
时间:2010-09-27 来源:兴说:
Union 可以将具有不同含义或不同结构的数据绑定在一起。
let Volume =
| Liter of float
| UsPint of float
| ImperialPint of float
let vol1 = Liter 2.5
let vol2 = UsPint 2.5
let vol3 = ImperialPint 2.5
let convertVolumeToLiter x =
match x with
| Liter x -> x
| UsPint -> x * 0.473
| ImperialPint x -> x * 0.568
printfn convertVolumeToLiter vol1
printfn convertVolumeToLiter vol2
printfn convertVolumeToLiter vol3
#light
type 'a BinaryTree =
| BinaryNode of 'a BinaryTree * 'a BinaryTree
| BinaryValue of 'a
let tree1 =
BinaryNode( //根节点
BinaryNode( BinaryValue 1, BinaryValue 2), //子节点1,具有1跟2两个叶子
BinaryNode( BinaryValue 3, BinaryValue 4) ) //子节点2,具有3跟4两个叶子
//看到了么,这里我们借助一个范式的类型 BinaryTree,就很自然的表现出了一颗二叉树。
//它有一个根节点,两个子节点,然后每个子节点又有两个值。
//然后是利用模式匹配来输出这棵树
let rec printBinaryTreeValues x =
match x
| BinaryNode (node1, node2) ->
printBinaryTreeValues node1;
printBinaryTreeValues node2
| BinaryValue x -> printfn x;printfn ", "
type Tree<'a> =
| Node of Tree<'a> list
| Value of 'a
let tree2 =
Node( [ Node( [Value "one"; Value "two"] );
Node( [Value "three"; Value "four"]) ] )
let rec printTreeValues x =
match x with
| Node l -> List.iter printTreeValues l
| Value x ->
printfn x;printfn ","
他的使用方式我用例子来讲解吧。
let Volume =
| Liter of float
| UsPint of float
| ImperialPint of float
let vol1 = Liter 2.5
let vol2 = UsPint 2.5
let vol3 = ImperialPint 2.5
看起来好像什么用也没有,是吧,别急,我们先来看看他的模式匹配。
let convertVolumeToLiter x =
match x with
| Liter x -> x
| UsPint -> x * 0.473
| ImperialPint x -> x * 0.568
printfn convertVolumeToLiter vol1
printfn convertVolumeToLiter vol2
printfn convertVolumeToLiter vol3
这里的模式匹配它可以接收一个范式定义的 Volume,然后判断他的类型,是Liter 还是 UsPint
或 ImperialPint ,然后对其做不同的处理。
嗯,还是感觉不到他的魔力,好吧,看下一个例子。
这个是一个完全二叉树的例子,唯一的区别就是,在这里节点是没有值的,只有最终的叶子才有值。
#light
type 'a BinaryTree =
| BinaryNode of 'a BinaryTree * 'a BinaryTree
| BinaryValue of 'a
let tree1 =
BinaryNode( //根节点
BinaryNode( BinaryValue 1, BinaryValue 2), //子节点1,具有1跟2两个叶子
BinaryNode( BinaryValue 3, BinaryValue 4) ) //子节点2,具有3跟4两个叶子
//看到了么,这里我们借助一个范式的类型 BinaryTree,就很自然的表现出了一颗二叉树。
//它有一个根节点,两个子节点,然后每个子节点又有两个值。
//然后是利用模式匹配来输出这棵树
let rec printBinaryTreeValues x =
match x
| BinaryNode (node1, node2) ->
printBinaryTreeValues node1;
printBinaryTreeValues node2
| BinaryValue x -> printfn x;printfn ", "
然后来看看一颗普通的树,当然,这里只是为了展示两种不同的定义方法而已。
type Tree<'a> =
| Node of Tree<'a> list
| Value of 'a
let tree2 =
Node( [ Node( [Value "one"; Value "two"] );
Node( [Value "three"; Value "four"]) ] )
let rec printTreeValues x =
match x with
| Node l -> List.iter printTreeValues l
| Value x ->
printfn x;printfn ","
相关阅读 更多 +