Created
January 10, 2014 20:58
-
-
Save zbroyar/8362465 to your computer and use it in GitHub Desktop.
Використання поліморфних структур разом з першокласними модулями дозволяють інкапсулювати варіанти реалізації.
У прикладі нижче модулі TI та TF будуть реалізовані окремими файлами.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
open Printf | |
module type T = sig | |
type t | |
val init : unit -> t | |
val get_msg : t -> t * string | |
end | |
type 'a global_context = { | |
g : float; (* global part of context *) | |
l : 'a (* implementation-specific part of context *) | |
} | |
let start_loop m = | |
let module I = (val m : T) in | |
let rec loop ctx = function | |
| 0 -> () | |
| counter -> | |
let l',str = I.get_msg ctx.l in | |
printf "Message: %s\n%!" str; | |
loop {ctx with l = l'} (counter - 1) | |
in | |
loop {g = 0.0; l = I.init()} 10 | |
module TI = struct | |
type t = int | |
let init () = 0 | |
let get_msg v = (v+1), string_of_int v | |
end | |
module TF = struct | |
type t = float | |
let init () = 0.0 | |
let get_msg v = (v +. 0.0001), string_of_float v | |
end | |
let _ = List.iter | |
(fun (n,m) -> | |
printf "Module %s:\n%!" n; | |
start_loop m | |
) | |
[ | |
"Int", (module TI : T); | |
"Float", (module TF : T) | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment