I am attempting to learn OCaml by using compiled code instead of the top-level; however, much of the sample code online seems to appeal to the latter.
I would like to create a new Foo within a method of an object per below. This code does not compile, citing a syntax error with the doFooProc definition.
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;;
Additionally, the ‘let’ syntax don’t seem to be friendly within class definitions. Why is that?
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 go about creating a new object of class foo in the doFooProc method and call the instantiated foo’s process command?
You’re mostly correct, but are either confusing syntax with the module system, or thinking of other languages. Take my considerations and you should be good!
Lowercase ‘foo’ for objects, modules are uppercase. Also, you must put the definition of foo above the object that calls it. You should get an
Unbound class fooif this happens.Because you don’t have a matching
in, instead you have a semi-colon. Then it will work. Also, you can remove those extra parens, but it doesn’t matter.Yes. It’s just like writing mutually recursive functions and modules, you connect them with the
andkeyword.