记录中的显式多态类型 [英] Explicit polymorphic type in record
问题描述
在OCaml中,可以在记录中定义显式多态类型
type foo = { f : 'a. unit -> 'a };;
似乎我们只能像
type foo = { f : 'a. unit -> 'a };;
那样为f
分配常规值
{ f = fun () -> failwith ""; }
或
{ f = fun () -> exit 1; }
如何在现实世界中使用此语言功能?有什么好的实际例子吗?
这与记录并没有真正的联系.如果您声明任何具有类型'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
如果您想将像List.length
这样的函数作为参数传递给另一个函数,并使其在多种类型上使用,它将很有用:
假设我们要将List.length
传递给test
.我们不能直接做到这一点:
# 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
但是我们可以使用一条记录:
# let test foo = foo.f [1;2;3] + foo.f ["a";"b";"c"];;
val test : foo -> int = <fun>
# test foo;;
- : int = 6
In OCaml, it is possible to define explicit polymorphic type in a record
type foo = { f : 'a. unit -> 'a };;
It seems we can assign only general values to f
like
{ f = fun () -> failwith ""; }
or
{ f = fun () -> exit 1; }
How to use this language feature in real world? Is there any good practical example?
This isn't really connected with records. If you declare any function to have type 'a. unit -> 'a
(takes nothing and returns whatever the caller wanted) then you can only use it for functions that don't return.
Here's a slightly more useful example: a record containing a function for finding the length of lists (of any type).
# 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
It can be useful if you wanted to pass a function like List.length
as an argument to another function, and have it use it on multiple types:
Say we want to pass List.length
to test
. We can't do it directly:
# 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
But we can use a record:
# let test foo = foo.f [1;2;3] + foo.f ["a";"b";"c"];;
val test : foo -> int = <fun>
# test foo;;
- : int = 6
这篇关于记录中的显式多态类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!