Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive functions within OCaml objects

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;;
like image 375
Mat Kelly Avatar asked Aug 11 '26 04:08

Mat Kelly


1 Answers

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.

like image 152
Kurt Schelfthout Avatar answered Aug 12 '26 21:08

Kurt Schelfthout



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!