Recursive Functions in OCaml Objects

I am trying to calculate recursion for OCaml in the context of an object method. I tried the following code but cannot compile it.

class foo =
object (self)
 method loopTest =
  let rec doIt x =
   Printf.printf "%d\n" x;
   if x>1 then doIt (x+1)
end;;

How to create a recursive function of this type inside 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;;
+3
source share
3 answers

You still need to call doIt in the loopTest method. letjust defines doIt, just as it methodsimply defines a method and does not call it. The compiler detects this because it does not know what to return from loopTest (for example, a method that does not have a return type of void but does not have an implementation in C # or Java).

, , , if x>1 then doIt (x-1), doIt 100 - .

+3

OCaml , , . , testLoop doIt, in in doIt .

+2

Two infinite loops in one code;), you should learn about Iterators, I think;)

-1
source

Source: https://habr.com/ru/post/1704433/


All Articles