首页 > 解决方案 > 在 Ocaml 中调用嵌套对象中的方法的语法

问题描述

我是 OCaml 的新手,我正在尝试创建一个使用堆栈的程序。所以这就是我所做的:

  1. 我有一个对象(后来定义了 ob_ctx),它有几个字段定义如下:

type my_custom_type = {
      nb_locals: int;
      mutable label_br: stack_of_string;
}
  1. 我有类stack_of_string:
    class stack_of_string =
        object (self)
          val mutable the_list = ( [] : string list )
          method push x =                        
            the_list <- x :: the_list
          method pop =                          
            let result = List.hd the_list in
            the_list <- List.tl the_list;
            result
          method peek =                          
            List.hd the_list
          method size =                        
            List.length the_list
        end;;
  1. 我尝试了终端中的类和方法,它们似乎工作正常,但是当我在文件中的函数中尝试这个时,它不起作用:
let my_fct ctx = 
ctx.label_br#push ( function_that_returns_a_string() );
(*or ctx.label_br#push ( "a simple string" );  *)
(*or ctx.label_br#push "a simple string" ;  *)
let some_other_var = "sth" in ....

它说

错误:此函数的类型为 string -> unit 应用于太多参数;也许你忘记了一个';'。命令以代码 2 退出

我不明白为什么有太多参数,推送需要 1 个参数,而我给出了 1 个参数。有人可以解释一下吗

提前致谢

标签: ocaml

解决方案


您没有为my_fct. 我使用了以下定义:

let my_fct ctx = 
    ctx.label_br#push ( String.make 3 'x' );
    let some_other_var = "sth" in some_other_var

有了这个定义(和上面的其他定义),你的代码对我来说编译得很好。

造成这种情况的一个可能原因是您的 OCaml 会话中有剩余的定义,这些定义令人困惑。您可以尝试从头开始。我希望您会看到我所做的相同的事情,即代码编译正常。

如果没有,您应该给出一个完整的(独立的)示例,以引发您所看到的错误。否则很难提供帮助。


推荐阅读