This site is updated infrequently. For up-to-date information, please visit the new OCaml website at ocaml.org.

Mutually recursive functions in different modules
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
 Date: 2007-09-19 (08:42) From: Julien Signoles Subject: Re: [Caml-list] Mutually recursive functions in different modules
```Hello,

> Is it possible to have mutually recursive functions in separate modules?

I know (at least) 4 solutions to your problem: one use recursive modules
as suggested by Jacques Garrigue, one use higher-order functions as
suggested by Jean-Christophe Filliatre, one use functors and one use
references on functions.

For example, if you want something (stupid) like

module A = struct let f x = if x <= 0 then 0 else B.f (x - 2) end
module B = struct let f x = if x = 1 then 1 else A.f (x - 2) end

you can write:

(* 1- using recursive modules *)
module rec A : sig val f : int -> int end = struct
let f x = if x <= 0 then 0 else B.f (x - 2)
end and B : sig val f : int -> int end = struct
let f x = if x = 1 then 1 else A.f (x - 2)
end

(* 2- using higher-order functions *)
module A' = struct let f g x = if x <= 0 then 0 else g (x - 2) end
module B = struct let rec f x = if x = 1 then 1 else A'.f f (x - 2) end
module A = struct let f = A'.f B.f end

(* 3- using functors *)
module FA(X:sig val f : int -> int end) = struct
let f x = if x <= 0 then 0 else X.f (x - 2)
end
module B = struct
let rec f x =
let module A = FA(struct let f = f end) in
if x = 1 then 1 else A.f (x - 2)
end
module A = FA(struct let f = B.f end)

(* 4- using references on functions *)
module A' = struct let f = ref (fun _ -> assert false) end
module B = struct let f x = if x = 1 then 1 else !A'.f (x - 2) end
module A = struct
let () = A'.f := fun x -> if x <= 0 then 0 else B.f (x - 2)
let f = !A'.f
end

In my opinion, solution 1 is the more natural when A and B are in the
same file.

Hope this helps,
Julien
--
mailto:Julien.Signoles@lri.fr ; http://www.lri.fr/~signoles
"In theory, practice and theory are the same,
but in practice they are different" (Larry McVoy)

```