我在使用 ocaml 多态函数时遇到了一些麻烦

I got some trouble with ocaml polymorphic function

我需要你的帮助,请问我的代码错误在哪里?

let create = Array.make_matrix 10 10;;

let assoc int = create int,create (char_of_int int);;

错误是

3 | let assoc int = create int,create (char_of_int int);;
                                      ^^^^^^^^^^^^^^^^^
Error: This expression has type char but an expression was expected of type
         int

当你在 Ocaml 上隐式定义一个多态函数时,它有一个“弱类型”,这意味着在你调用它一次之后,一个类型肯定会分配给函数,所以因为你调用了一个 int,它现在有一个 int -> int 数组类型,并且不接受 char 作为参数。

这就是“价值限制”。您可以通过这样定义 create 来使其工作:

let create v = Array.make_matrix 10 10 v

它是这样工作的:

# let create v = Array.make_matrix 10 10 v;;
val create : 'a -> 'a array array = <fun>

# let assoc int = create int,create (char_of_int int);;
val assoc : int -> int array array * char array array = <fun>

值限制指出只有“值”(在某种意义上)可以是多态的;特别是,仅应用函数的表达式不能完全多态。您通过仅将函数应用于某些值来定义 create,因此值限制可防止它成为多态的。上面的定义将 create 定义为 lambda(OCaml 中的 fun),这是每个值限制的“值”。所以它可以是完全多态的。

您可以在 Chapter 5 of the OCaml manual 中阅读有关值限制的信息。