Import Upstream version 20180207
[hcoop/debian/mlton.git] / lib / mlton / env / poly-cache.fun
CommitLineData
7f918cf1
CE
1(* Copyright (C) 1999-2006 Henry Cejtin, Matthew Fluet, Suresh
2 * Jagannathan, and Stephen Weeks.
3 *
4 * MLton is released under a BSD-style license.
5 * See the file MLton-LICENSE for details.
6 *)
7
8functor PolyCache(): POLY_CACHE =
9struct
10
11datatype ('a, 'b) t = T of {equal: ('a * 'a) -> bool,
12 elts: ('a * 'b) list ref}
13
14fun fromList{equal, elements} = T{equal = equal, elts = ref elements}
15
16fun new{equal} = T{equal = equal, elts = ref []}
17
18fun toList(T{elts, ...}) = !elts
19
20fun size c = List.length(toList c)
21fun foreach(c, f) = List.foreach(toList c, f)
22
23fun peek(T{equal, elts = ref l}, x) =
24 case List.peek(l, fn (x', _) => equal(x, x')) of
25 NONE => NONE
26 | SOME(_, y) => SOME y
27
28fun lookup cx = valOf(peek cx)
29
30fun toFunction c a = lookup(c, a)
31
32fun addNew(T{elts = r as ref l, ...}, x, y) = r := (x, y) :: l
33
34fun getOrAdd(c, x, th) =
35 case peek(c, x) of
36 NONE => let val y = th()
37 in addNew(c, x, y) ; y
38 end
39 | SOME y => y
40
41fun eq(T{elts=r, ...}, T{elts=r', ...}) = r = r'
42
43end
44
45structure PolyCache = PolyCache()