Je voulais jouer avec les types fantômes, mais je crois mal connaître le fonctionnement des modules dans OCaml, car le code suivant compile sans problème:
SafeString.mli:
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10 module SafeString : sig type 'a t type safe type unsafe val new_string : string -> unsafe t val unsafe_to_safe : unsafe t -> safe t val exec_sql : safe t -> unit end
SafeString.ml
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 module SafeString = struct type 'a t = Str of string type safe type unsafe let new_string s = Str s let unsafe_to_safe unsafe_str = match unsafe_str with | Str s -> Str ("[SAFE] " ^ s) let exec_sql s = match s with | Str s -> Printf.printf "select * from tbl where id=%s\n" s end let _ = let s = SafeString.new_string "'world" in SafeString.exec_sql s
Compilation/exécution:
Je me serais attendu à ce que la compilation de SafeString.ml échoue, car j'essaye de passer un unsafe SafeString.t à une fonction qui doit recevoir un safe SafeString.t.
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5 19:49 vince@archvince:~/prog/ocaml/phantom$ ocamlopt SafeString.mli 19:49 vince@archvince:~/prog/ocaml/phantom$ ocamlopt SafeString.ml 19:49 vince@archvince:~/prog/ocaml/phantom$ ./a.out select * from tbl where id='world
Est-ce que quelqu'un pourrait me démêler S.V.P.?
Merci,
Vincent.
Partager