mirror of
https://github.com/c-cube/ocaml-containers.git
synced 2025-12-06 03:05:28 -05:00
add CCKlist.memoize for costly computations
This commit is contained in:
parent
ec0e92da35
commit
fdcba1122d
4 changed files with 37 additions and 2 deletions
|
|
@ -72,6 +72,7 @@ CCFQueue
|
|||
CCFlatHashtbl
|
||||
CCHashSet
|
||||
CCHashTrie
|
||||
CCImmutArray
|
||||
CCIntMap
|
||||
CCMixmap
|
||||
CCMixset
|
||||
|
|
|
|||
|
|
@ -67,7 +67,7 @@ val stdout : t
|
|||
val stderr : t
|
||||
|
||||
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
|
||||
(** Print to the given file *)
|
||||
(** Print to the given file *)
|
||||
|
|
|
|||
|
|
@ -441,6 +441,36 @@ let sort_uniq ?(cmp=Pervasives.compare) l =
|
|||
let l = to_list l in
|
||||
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} *)
|
||||
|
||||
let rec interleave a b () = match a() with
|
||||
|
|
|
|||
|
|
@ -191,6 +191,10 @@ val sort_uniq : ?cmp:'a ord -> 'a t -> 'a t
|
|||
finite. O(n ln(n)) time and space.
|
||||
@since 0.3.3 *)
|
||||
|
||||
val memoize : 'a t -> 'a t
|
||||
(** Avoid recomputations by caching intermediate results
|
||||
@since NEXT_RELEASE *)
|
||||
|
||||
(** {2 Fair Combinations} *)
|
||||
|
||||
val interleave : 'a t -> 'a t -> 'a t
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue