使用DU(Discriminated Union类型),如何执行类型测试模式匹配?我有以下运行代码:
type IU =
|Int of int
|Unit of Unit
let x = IU.Int(3)
let y = IU.Unit(())
let z = [3.14]
let showI (v) =
match box v with
| :? IU ->
match v with
| Int(_) -> "an IU int"
|_ -> "not a IU.int"
|_ -> "not a IU.int"
Run Code Online (Sandbox Code Playgroud)
但我对showI函数中的内部匹配不满意.我更喜欢这样的东西:
let showI (v) =
match box v with
| :? IU.Int -> "an int"
|_ -> "not a IU.int"
Run Code Online (Sandbox Code Playgroud)
哪个不编译(错误:未定义Int类型).
我错过了明显的语法吗?谢谢.
注意:showI函数接受具有未知类型的变量; 这就是臭盒v的原因.
正如其他人所指出的那样,我认为没有任何内置的语言功能可以让你这样做.但是,您可以定义执行类型测试的活动模式:
let (|IsIU|_|) (candidate : obj) =
match candidate with
| :? IU as iu -> Some iu
| _ -> None
Run Code Online (Sandbox Code Playgroud)
此活动模式具有类型obj -> IU option.
您可以使用标准模式构建自己的自定义活动模式,如下所示:
let showI = function
| IsIU (IU.Int i) -> "an IU int"
| _ -> "not a IU.int"
Run Code Online (Sandbox Code Playgroud)
在此示例中,自定义IsIU活动模式由与IU.Int案例匹配的标准标识符模式组成.
这里的显示与使用情况的样本FSI会话x,y以及z在OP给定的值:
> showI x;;
val it : string = "an IU int"
> showI y;;
val it : string = "not a IU.int"
> showI z;;
val it : string = "not a IU.int"
Run Code Online (Sandbox Code Playgroud)