Hello.

  I need to create two functions that share common state, and I want to
create this common state once per program run, and I want to make each
function call very cheap.  When I'm doing it naively, I get "value restriction":

$ ocaml
# #use "topfind";;
# #camlp4r;;
# type func 'a 'r = string -> ('a -> 'r) -> 'r;
type func 'a 'b = string -> ('a -> 'b) -> 'b
# value mkpair1 from_string =
  (* some common values here *)
  ( fun s f -> try f (from_string s) with [e -> failwith "mkpair1"]
  , fun s f -> try f (Some (from_string s)) with [e -> f None]
  );
value mkpair1 :
  ('a -> 'b) -> ('a -> ('b -> 'c) -> 'c * 'a -> (option 'b -> 'd) -> 'd) = <fun>
# value identity x = x;
value identity : 'a -> 'a = <fun>
# value (id11, id12) = mkpair1 identity;
value id11 : '_a -> ('_a -> '_b) -> '_b = <fun>
value id12 : '_a -> (option '_a -> '_b) -> '_b = <fun>

  But I've found a trick that uses rank-2 polymorphism of record fields:

# type pair 'a 'b =
     { notnull : !'r . func 'a 'r
     ; nullable : !'r . func (option 'a) 'r
     };
type pair 'a 'b =
  { notnull : !'c. func 'a 'c; nullable : !'d. func (option 'a) 'd }
# value mkpair2 from_string =
  (* some common values here *)
  { notnull = fun s f -> try f (from_string s) with [e -> failwith "mkpair2"]
  ; nullable = fun s f -> try f (Some (from_string s)) with [e -> f None]
  };
value mkpair2 : (string -> 'a) -> pair 'a 'b = <fun>
# value { notnull = id21 ; nullable = id22 } = mkpair2 identity;
value id21 : func string 'a = <fun>
value id22 : func (option string) 'a = <fun>
#

  And everything seems to work: the record is created once, then
it is "decomposed" to id21 and id22 functions (either right after its
creation or on each call, it should be cheap anyway).  But I don't
know whether this solution is correct and will it remain correct in
future versions of OCaml -- can you help me here?

-- 
Caml-list mailing list.  Subscription management and archives:
https://sympa-roc.inria.fr/wws/info/caml-list
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners
Bug reports: http://caml.inria.fr/bin/caml-bugs

Reply via email to