在 Ocaml 的嵌套对象中调用方法的语法
syntax for calling a method in nested objects in Ocaml
我是 OCaml 的新手,我正在尝试创建一个使用堆栈的程序。所以这就是我所做的:
- 我有一个对象(稍后定义 ob_ctx),它有几个定义如下的字段:
type my_custom_type = {
nb_locals: int;
mutable label_br: stack_of_string;
}
- 我有 class 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;;
- 我尝试了 class 和终端中的方法,它们似乎工作正常,但是当我在我的文件中的函数中尝试它时它不起作用:
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 ....
它说
Error: This function has type string -> unit
It is applied to too many arguments; maybe you forgot a `;'. Command exited with code 2
我不明白为什么参数太多了,推送需要 1 个参数,而我给出了 1 个参数。谁能给我解释一下
提前致谢
您没有给出 my_fct
的完整(或 self-contained)定义。我使用了以下定义:
let my_fct ctx =
ctx.label_br#push ( String.make 3 'x' );
let some_other_var = "sth" in some_other_var
使用这个定义(以及上面的其他定义),你的代码对我来说编译得很好。
一个可能的原因是您在 OCaml 会话中有剩余的定义,这些定义令人困惑。您可以尝试从头开始。我希望您会看到我所做的同样的事情,即代码编译正常。
如果不是,您应该给出一个完整的 (self-contained) 示例来引出您所看到的错误。不然很难帮忙。
我是 OCaml 的新手,我正在尝试创建一个使用堆栈的程序。所以这就是我所做的:
- 我有一个对象(稍后定义 ob_ctx),它有几个定义如下的字段:
type my_custom_type = {
nb_locals: int;
mutable label_br: stack_of_string;
}
- 我有 class 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;;
- 我尝试了 class 和终端中的方法,它们似乎工作正常,但是当我在我的文件中的函数中尝试它时它不起作用:
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 ....
它说
Error: This function has type string -> unit It is applied to too many arguments; maybe you forgot a `;'. Command exited with code 2
我不明白为什么参数太多了,推送需要 1 个参数,而我给出了 1 个参数。谁能给我解释一下
提前致谢
您没有给出 my_fct
的完整(或 self-contained)定义。我使用了以下定义:
let my_fct ctx =
ctx.label_br#push ( String.make 3 'x' );
let some_other_var = "sth" in some_other_var
使用这个定义(以及上面的其他定义),你的代码对我来说编译得很好。
一个可能的原因是您在 OCaml 会话中有剩余的定义,这些定义令人困惑。您可以尝试从头开始。我希望您会看到我所做的同样的事情,即代码编译正常。
如果不是,您应该给出一个完整的 (self-contained) 示例来引出您所看到的错误。不然很难帮忙。