Commit | Line | Data |
---|---|---|
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 | ||
8 | functor PolyCache(): POLY_CACHE = | |
9 | struct | |
10 | ||
11 | datatype ('a, 'b) t = T of {equal: ('a * 'a) -> bool, | |
12 | elts: ('a * 'b) list ref} | |
13 | ||
14 | fun fromList{equal, elements} = T{equal = equal, elts = ref elements} | |
15 | ||
16 | fun new{equal} = T{equal = equal, elts = ref []} | |
17 | ||
18 | fun toList(T{elts, ...}) = !elts | |
19 | ||
20 | fun size c = List.length(toList c) | |
21 | fun foreach(c, f) = List.foreach(toList c, f) | |
22 | ||
23 | fun 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 | ||
28 | fun lookup cx = valOf(peek cx) | |
29 | ||
30 | fun toFunction c a = lookup(c, a) | |
31 | ||
32 | fun addNew(T{elts = r as ref l, ...}, x, y) = r := (x, y) :: l | |
33 | ||
34 | fun 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 | ||
41 | fun eq(T{elts=r, ...}, T{elts=r', ...}) = r = r' | |
42 | ||
43 | end | |
44 | ||
45 | structure PolyCache = PolyCache() |