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;;

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.