Create objects on the fly in OCaml

I am trying to learn OCaml using compiled code instead of the top level; however, most of the sample code online seems to refer to the latter.

I would like to create a new Foo in an object method as per below. This code does not compile, referencing a syntax error with the definition of doFooProc.

class bar = object (self) method doFooProc = (new Foo "test")#process end;; class foo (param1:string)= object (self) method process = Printf.printf "%s\n" "Processing!" initializer Printf.printf "Initializing with param = %s\n" param1 end;; 

Also, the let syntax does not seem friendly in class definitions. Why is this?

 class bar = object (self) method doFooProc = let xxx = (new Foo "test"); xxx#process end;; class foo (param1:string)= object (self) method process = Printf.printf "%s\n" "Processing!" initializer Printf.printf "Initializing with param = %s\n" param1 end;; 

How do I deal with creating a new object of class foo in the doFooProc method and calling the instantiated process command foo?

+4
source share
2 answers

You are mostly right, but either confuse the syntax with a modular system, or think of other languages. Take my thoughts and you should be good!

I would like to create a new Foo as part of an object method for below. This code does not compile, citing a syntax error with doFooProc.

Lower case "foo" for objects, modules in upper case. In addition, you must place the definition of foo over the object calling it. You should get an Unbound class foo if that happens.

 class bar = object (self) method doFooProc = (new foo "test")#process end;; 

Also, the let syntax does not seem friendly in class definitions. Why is this?

Since you don't have a corresponding in , you have a semicolon instead. Then it will work. In addition, you can remove these additional parades, but it does not matter.

 class bar = object (self) method doFooProc = let xxx = (new Foo "test") in xxx#process end;; 

If, say, the method in foo created the bar as well, is there a way to avoid the problem that arises with the ordering of class definitions inside the source file?

Yes. This is similar to writing mutually recursive functions and modules, you associate them with the and keyword.

 class bar = object (self) method doFooProc = (new foo "test")#process end and foo (param1:string) = object (self) method process = Printf.printf "%s\n" "Processing!" initializer Printf.printf "Initializing with param = %s\n" param1 end 
+2
source

For two mutually recursive classes, use the keyword

 class bar = object (self) method doFooProc = let xxx = (new foo "test") in xxx#process end and foo (param1:string)= object (self) method process = Printf.printf "%s\n" "Processing!" initializer Printf.printf "Initializing with param = %s\n" param1 method bar = new bar end;;` 
+2
source

All Articles