aNormalPerson
aNormalPerson

Reputation: 53

syntax for calling a method in nested objects in Ocaml

I'm new to OCaml and I was trying to create a program that uses a stack. So here is what I did:

  1. I have an object (later defined ob_ctx) that has a few fields defined as follows:

type my_custom_type = {
      nb_locals: int;
      mutable label_br: stack_of_string;
}
  1. I have the 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;;
  1. I tried the class and the methods in terminal and they seem to work fine, but when I try this in a function in my file it does not work:
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 ....

It says

Error: This function has type string -> unit It is applied to too many arguments; maybe you forgot a `;'. Command exited with code 2

I don't understand how is that too many arguments, the push takes 1 argument and I gave 1 argument. Could someone please explain it me

Thanks in advance

Upvotes: 0

Views: 93

Answers (1)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66813

You don't give a complete (or self-contained) definition for my_fct. I used the following definition:

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

With this definition (and the other definitions above), your code compiles fine for me.

One possible cause for this is that you have leftover definitions in your OCaml session that are confusing things. You might try starting again from scratch. I would expect that you'll see the same thing I do, i.e., that the code compiles OK.

If not, you should give a full (self-contained) example that elicits the error you're seeing. Otherwise it's very difficult to help.

Upvotes: 2

Related Questions