Reputation: 2366
I am trying to figure out recursion for OCaml in the context of an object's method. I have tried the following code but can't seem to get it to compile.
class foo =
object (self)
method loopTest =
let rec doIt x =
Printf.printf "%d\n" x;
if x>1 then doIt (x+1)
end;;
How do I create a recursive function of this sort within a method?
Revised code:
class foo =
object (self)
method loopTest =
let rec doIt x =
Printf.printf "%d\n" x;
if x<10 then doIt (x+1) in doIt 0
end;;
Upvotes: 3
Views: 1892
Reputation: 8980
You still need to call doIt in your loopTest method. let
just defines doIt, just like method
just defines a method, and does not call it. The compiler detects this because it doesn't know what to return from loopTest (like a method that does not have return type void, but has no implementation in C# or Java).
Also, you're in for an infinite loop with this code, maybe if x>1 then doIt (x-1)
followed by doIt 100
is a better idea.
Upvotes: 4
Reputation: 40336
My OCaml is rusty, but I don't think let evaluates to what it bound. If you want testLoop to call doIt, tack on a in doIt or similar.
Upvotes: 2