File: weak.3.sml

package info (click to toggle)
mlton 20130715-3
  • links: PTS
  • area: main
  • in suites: stretch
  • size: 60,900 kB
  • ctags: 69,386
  • sloc: xml: 34,418; ansic: 17,399; lisp: 2,879; makefile: 1,605; sh: 1,254; pascal: 256; python: 143; asm: 97
file content (23 lines) | stat: -rw-r--r-- 719 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
fun find cache x =
   case (List.find (fn (y,_) => x = y) (!cache)) of
      NONE => NONE
    | SOME (_,r) => SOME r
fun remove cache x =
   cache := (List.filter (fn (y,_) => not (x = y)) (!cache))
fun insert cache (x,r) =
   cache := (x,r)::(!cache)

val cache = ref []

fun lookup (x : int) =
   case find cache x of
      SOME r  => (case MLton.Weak.get r of
                     SOME r' => r'
                   | NONE => (remove cache x; lookup x))
    | NONE    => let val res = x + 1
                     val wres = MLton.Weak.new res
                 in insert cache (x, wres);
                    res
                 end

val _ = List.app (fn x => print (concat [Int.toString (lookup x), "\n"])) [5,4,3,2,1]