views:

243

answers:

3

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;;
+1  A: 

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.

Logan Capaldo
+2  A: 

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.

Kurt Schelfthout
A: 

Two infinite loops in the same code ;), you should learn about Iterators I guess;)

martani_net
that's true dude :D
martani_net