OCaml 中声明类型时怎样限定为某个 Variant type 中的某个 case?

这是不可行的,即在编译期是无法进行这样的类型检查的。考虑这样的例子:type my_type=constr1 | constr2 ;;let a=contr1 ;;let func arg= ... ;;func a ;;a的类型是my_type,编译器做类型检查时只会为a的类型标注为my_type,仅此而已,它不会标注上是constr1建立的值或是constr2建立的值。自然像let func : constr2=... ;;这样的类型标注没有意义,constr2不是编译器计算的类型,在编译期无法检查出来。PS.或许可以这样解决:type my_type1=constr1and my_type2=constr2and my_type12= case1 of my_type1 |case2 of my_type2 ;;let func (arg : my_type2)= ... ;;如果要用my_type1和my_type2的union类型,就这样写:let func (arg : my_type12)= ... ;;这样就可以在编译期进行限定,只不过使用时再多包裹了一层constructor
■网友
你可以用 polymorphic variants .type my_type = type case2 = let func: case2 = ...
■网友
额不知道OCaml的variant type和F#的discriminated union有多大区别,但是my_type本身是type,case1 case2不是type,或者用single case?


    推荐阅读