记录中的显式多态类型

Sta*_*tas 1 ocaml

在OCaml中,可以在记录中定义显式多态类型

type foo = { f : 'a. unit -> 'a };;
Run Code Online (Sandbox Code Playgroud)

看来我们只能分配一般值f喜欢

{ f = fun () -> failwith ""; }
Run Code Online (Sandbox Code Playgroud)

要么

{ f = fun () -> exit 1; }
Run Code Online (Sandbox Code Playgroud)

如何在现实世界中使用这种语言功能?有什么好的实际例子吗?

Tho*_*ard 5

这与记录无关.如果声明任何函数具有类型'a. unit -> 'a(不接受任何内容并返回调用者想要的任何内容),那么您只能将它用于不返回的函数.

这是一个稍微有用的示例:包含用于查找列表长度(任何类型)的函数的记录.

# type foo = { f : 'a. 'a list -> int };;
type foo = { f : 'a. 'a list -> int; }

# let foo = { f = List.length };;
val foo : foo = {f = <fun>}
# foo.f [1;2;3];;
- : int = 3
Run Code Online (Sandbox Code Playgroud)

如果你想将一个函数List.length作为参数传递给另一个函数,并让它在多种类型上使用它,它会很有用:

说我们想传递List.lengthtest.我们不能直接这样做:

# let test fn = fn [1;2;3] + fn ["a";"b";"c"];;
Error: This expression has type string but an expression was expected of type
         int
Run Code Online (Sandbox Code Playgroud)

但我们可以使用记录:

# let test foo = foo.f [1;2;3] + foo.f ["a";"b";"c"];;
val test : foo -> int = <fun>

# test foo;;
- : int = 6
Run Code Online (Sandbox Code Playgroud)