add CCKlist.memoize for costly computations

This commit is contained in:
Simon Cruanes 2015-10-01 18:54:17 +02:00
parent ec0e92da35
commit fdcba1122d
4 changed files with 37 additions and 2 deletions

View file

@ -72,6 +72,7 @@ CCFQueue
CCFlatHashtbl CCFlatHashtbl
CCHashSet CCHashSet
CCHashTrie CCHashTrie
CCImmutArray
CCIntMap CCIntMap
CCMixmap CCMixmap
CCMixset CCMixset

View file

@ -67,7 +67,7 @@ val stdout : t
val stderr : t val stderr : t
val sprintf : ('a, t, unit, string) format4 -> 'a val sprintf : ('a, t, unit, string) format4 -> 'a
(** print into a string *) (** print into a string *)
val to_file : string -> ('a, t, unit, unit) format4 -> 'a val to_file : string -> ('a, t, unit, unit) format4 -> 'a
(** Print to the given file *) (** Print to the given file *)

View file

@ -441,6 +441,36 @@ let sort_uniq ?(cmp=Pervasives.compare) l =
let l = to_list l in let l = to_list l in
uniq (fun x y -> cmp x y = 0) (of_list (List.sort cmp l)) uniq (fun x y -> cmp x y = 0) (of_list (List.sort cmp l))
type 'a memoize =
| MemoThunk
| MemoSave of [`Nil | `Cons of 'a * 'a t]
let rec memoize f =
let r = ref MemoThunk in
fun () -> match !r with
| MemoSave l -> l
| MemoThunk ->
let l = match f() with
| `Nil -> `Nil
| `Cons (x, tail) -> `Cons (x, memoize tail)
in
r := MemoSave l;
l
(*$R
let printer = Q.Print.(list int) in
let gen () =
let rec l = let r = ref 0 in fun () -> incr r; `Cons (!r, l) in l
in
let l1 = gen () in
assert_equal ~printer [1;2;3;4] (take 4 l1 |> to_list);
assert_equal ~printer [5;6;7;8] (take 4 l1 |> to_list);
let l2 = gen () |> memoize in
assert_equal ~printer [1;2;3;4] (take 4 l2 |> to_list);
assert_equal ~printer [1;2;3;4] (take 4 l2 |> to_list);
*)
(** {2 Fair Combinations} *) (** {2 Fair Combinations} *)
let rec interleave a b () = match a() with let rec interleave a b () = match a() with

View file

@ -191,6 +191,10 @@ val sort_uniq : ?cmp:'a ord -> 'a t -> 'a t
finite. O(n ln(n)) time and space. finite. O(n ln(n)) time and space.
@since 0.3.3 *) @since 0.3.3 *)
val memoize : 'a t -> 'a t
(** Avoid recomputations by caching intermediate results
@since NEXT_RELEASE *)
(** {2 Fair Combinations} *) (** {2 Fair Combinations} *)
val interleave : 'a t -> 'a t -> 'a t val interleave : 'a t -> 'a t -> 'a t