Commit 1c54abc7 authored by POTTIER Francois's avatar POTTIER Francois

New function [visibly_memoize].

parent b3182635
......@@ -5,6 +5,10 @@
* In `Gensym`, new abstract type `generator`,
with three functions `generator`, `fresh`, and `current`.
* In `Memoize`, new function `visibly_memoize`,
which not only returns a memoized function,
but also provides outside access to the memoization table.
## 2018/11/30
* New release, including new modules (`Gensym`, `Memoize`,
......
......@@ -38,13 +38,22 @@ module Make (M : IMPERATIVE_MAPS) = struct
[let memoize f = fix (fun _ x -> f x)]. The following direct definition is
perhaps easier to understand and may give rise to more efficient code. *)
let memoize (f : key -> 'a) : key -> 'a =
type 'a t =
'a M.t
let visibly_memoize (f : key -> 'a) : (key -> 'a) * 'a t =
let table = M.create() in
fun x ->
let f x =
try
M.find x table
with Not_found ->
add x (f x) table
in
f, table
let memoize (f : key -> 'a) : key -> 'a =
let f, _table = visibly_memoize f in
f
let fix (ff : (key -> 'a) -> (key -> 'a)) : key -> 'a =
let table = M.create() in
......
......@@ -18,6 +18,7 @@ open Sigs
module Make
(M : IMPERATIVE_MAPS)
: MEMOIZER with type key = M.key
and type 'a t = 'a M.t
(* [ForOrderedType] is a special case of [Make] where it
suffices to pass an ordered type [T] as an argument.
......@@ -27,6 +28,7 @@ module Make
module ForOrderedType
(T : OrderedType)
: MEMOIZER with type key = T.t
and type 'a t = 'a Map.Make(T).t ref
(* [ForHashedType] is a special case of [Make] where it
suffices to pass a hashed type [T] as an argument. A
......@@ -35,6 +37,7 @@ module ForOrderedType
module ForHashedType
(T : HashedType)
: MEMOIZER with type key = T.t
and type 'a t = 'a Hashtbl.Make(T).t
(* [ForType] is a special case of [Make] where it suffices
to pass an arbitrary type [T] as an argument. A hash table
......
......@@ -114,7 +114,10 @@ module type MEMOIZER = sig
type key
(* A memoization combinator for this type. *)
val memoize: (key -> 'a) -> (key -> 'a)
(* A recursive memoization combinator for this type. *)
(* A memoization combinator where the memoization table is exposed. *)
type 'a t
val visibly_memoize: (key -> 'a) -> (key -> 'a) * 'a t
(* A recursive memoization combinator. *)
val fix: ((key -> 'a) -> (key -> 'a)) -> (key -> 'a)
(* [defensive_fix] works like [fix], except it additionally detects circular
dependencies, which can arise if the second-order function supplied by
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment