C'è un modo: functors mutuamente ricorsive. Vedi l'articolo this sulla compilazione separata in OCaml e nell'articolo ispiratore this che fornisce l'idea principale.
Ecco un esempio. Ho creato 4 interfaccia MLI-files:
$ ls *.mli
Make_moduleA.mli Make_moduleB.mli ModuleA.mli ModuleB.mli
e 3 di implementazione file:
$ ls *.ml
Make_moduleA.ml Make_moduleB.ml main.ml
Ecco il contenuto dei file di interfaccia:
(* ModuleA.mli *)
module type ModuleA = sig
val fa : int -> unit
end
(* ModuleB.mli *)
module type ModuleB = sig
val fb : int -> unit
end
(* Make_moduleA.mli *)
open ModuleA
open ModuleB
module type Make_moduleA_sig =
functor (Mb : ModuleB) ->
sig
val fa : int -> unit
end
module Make_moduleA : Make_moduleA_sig
(* Make_moduleB.mli *)
open ModuleA
open ModuleB
module type Make_moduleB_sig =
functor (Ma : ModuleA) ->
sig
val fb : int -> unit
end
module Make_moduleB : Make_moduleB_sig
e reciprocamente funtori ricorsive:
(* Make_moduleA.ml *)
open ModuleA
open ModuleB
module type Make_moduleA_sig =
functor (Mb : ModuleB) ->
sig
val fa : int -> unit
end
module Make_moduleA_impl =
functor (Mb : ModuleB) ->
struct
let rec fa (n : int) =
if n > 0 then
(Printf.printf "A: %d\n" n;
Mb.fb (n - 1))
end
module Make_moduleA = (Make_moduleA_impl : Make_moduleA_sig)
(* Make_moduleB.ml *)
open ModuleA
open ModuleB
module type Make_moduleB_sig =
functor (Ma : ModuleA) ->
sig
val fb : int -> unit
end
module Make_moduleB_impl =
functor (Ma : ModuleA) ->
struct
let rec fb (n : int) =
if n > 0 then
(Printf.printf "B: %d\n" n;
Ma.fa (n - 1))
end
module Make_moduleB = (Make_moduleB_impl : Make_moduleB_sig)
Ed ora combinare i moduli:
(* main.ml *)
open ModuleA
open ModuleB
open Make_moduleA
open Make_moduleB
module rec MAimpl : ModuleA = Make_moduleA(MBimpl)
and MBimpl : ModuleB = Make_moduleB(MAimpl)
let _ = (* just a small test *)
MAimpl.fa 4;
print_endline "--------------";
MBimpl.fb 4
Corporatura sequenza di comandi:
ocamlc -c ModuleA.mli
ocamlc -c ModuleB.mli
ocamlc -c Make_moduleA.mli
ocamlc -c Make_moduleB.mli
ocamlc -c Make_moduleA.ml
ocamlc -c Make_moduleB.ml
ocamlc -c main.ml
ocamlc Make_moduleA.cmo Make_moduleB.cmo main.cmo
I risultati dei test:
$ build.sh && ./a.out
A: 4
B: 3
A: 2
B: 1
--------------
B: 4
A: 3
B: 2
A: 1
fonte
2016-04-21 20:12:49
Potrebbe per favore fare un po 'di luce sul contesto di questo problema? Sono solo curioso: se è una sorta di codice generato automaticamente, allora perché preoccuparsi del tutto? –
Non è un codice generato automaticamente, ho già scritto queste funzioni ... – SoftTimur
Quanto è lungo quel file? Se è scritto manualmente, non lo dividerei (perché potresti perdere sia l'efficienza che la leggibilità). –