【问题标题】:syntax for calling a method in nested objects in Ocaml在 Ocaml 中调用嵌套对象中的方法的语法
【发布时间】:2020-10-16 22:08:37
【问题描述】:

我是 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 ....

它说

错误:此函数的类型为字符串 -> 单元 它适用于太多的论点;也许你忘记了一个';'。命令以代码 2 退出

我不明白为什么参数太多,推送需要 1 个参数,而我给出了 1 个参数。谁能给我解释一下

提前致谢

【问题讨论】:

    标签: ocaml


    【解决方案1】:

    您没有给出my_fct 的完整(或自包含)定义。我使用了以下定义:

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

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

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

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

    【讨论】:

    • "你可以尝试从头开始。"我按照你的建议做了,它有效!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2015-10-21
    • 2014-12-24
    • 1970-01-01
    • 1970-01-01
    • 2015-09-15
    • 2013-01-03
    • 2018-11-25
    • 1970-01-01
    相关资源
    最近更新 更多