在 OCaml 中,如何在模式匹配的不同分支中返回不同类型的值?
示例代码:
type t =
| Int of int
| Bool of bool
let f x =
match x with
| Int i -> i
| Bool b -> b
Run Code Online (Sandbox Code Playgroud)
但是,这将失败Error: This expression has type bool but an expression was expected of type int。
我尝试通过使用本地抽象类型来解决该问题:
type _ t =
| Int of int
| Bool of bool
let f (type a) (x : a t) : a =
match x with
| Int i -> i
| Bool b -> b
Run Code Online (Sandbox Code Playgroud)
然而,这也行不通。错误是Error: This expression has type int but an expression was expected of type a。
我做错了什么?是否有可能在模式匹配的每个分支中返回不同类型的值?
您提供的类型参数t实际上并没有受到任何限制,因此编译器只会将其推断为它首先遇到的任何内容,并在稍后遇到其他内容时抱怨。
您需要使用 GADT 根据所使用的构造函数指定类型参数的类型:
type _ t =
| Int: int -> int t
| Bool: bool -> bool t
Run Code Online (Sandbox Code Playgroud)
需要局部抽象类型来使类型细化工作,但其本身不执行任何操作。这是 GADT 在这里做的工作。