| 1 | fun find cache x = |
| 2 | case (List.find (fn (y,_) => x = y) (!cache)) of |
| 3 | NONE => NONE |
| 4 | | SOME (_,r) => SOME r |
| 5 | fun remove cache x = |
| 6 | cache := (List.filter (fn (y,_) => not (x = y)) (!cache)) |
| 7 | fun insert cache (x,r) = |
| 8 | cache := (x,r)::(!cache) |
| 9 | |
| 10 | val cache = ref [] |
| 11 | |
| 12 | fun lookup (x : int) = |
| 13 | case find cache x of |
| 14 | SOME r => (case MLton.Weak.get r of |
| 15 | SOME r' => r' |
| 16 | | NONE => (remove cache x; lookup x)) |
| 17 | | NONE => let val res = x + 1 |
| 18 | val wres = MLton.Weak.new res |
| 19 | in insert cache (x, wres); |
| 20 | res |
| 21 | end |
| 22 | |
| 23 | val _ = List.app (fn x => print (concat [Int.toString (lookup x), "\n"])) [5,4,3,2,1] |