【问题标题】:I got some trouble with ocaml polymorphic function我在使用 ocaml 多态函数时遇到了一些问题
【发布时间】:2021-07-06 11:27:56
【问题描述】:

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

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 ml caml toplevel


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      这是“价值限制”。您可以通过像这样定义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中的值限制。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-11-18
        • 2012-05-13
        • 1970-01-01
        • 1970-01-01
        • 2013-10-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多