Import Debian changes 20180207-1
[hcoop/debian/mlton.git] / regression / ref-flatten.4.sml
1 structure CList =
2 struct
3 datatype 'a clist' = Cons of 'a * 'a clist ref
4 withtype 'a clist = 'a clist' option
5
6 fun cnil () = NONE
7 fun ccons (h, t) = SOME (Cons (h, ref t))
8
9 fun match cl nilCase consCase =
10 case cl of
11 NONE => nilCase ()
12 | SOME (Cons (h, t)) => consCase (h, !t)
13
14 fun fromList l =
15 case l of
16 [] => cnil ()
17 | h::t => ccons (h, fromList t)
18
19 fun repeat x =
20 let
21 val r = ref NONE
22 val cl = SOME (Cons (x, r))
23 val () = r := cl
24 in
25 cl
26 end
27
28 local
29 val max = 1000
30 fun length' (cl, n) =
31 if n >= max
32 then NONE
33 else match cl
34 (fn () => SOME n)
35 (fn (_,t) => length' (t, n + 1))
36 in
37 fun length cl = length' (cl, 0)
38 end
39 end
40
41 val cl = CList.repeat #"x"
42 val n = CList.length cl
43 val () =
44 case n of
45 NONE => print "NONE\n"
46 | SOME n => print (concat ["SOME ", Int.toString n, "\n"])
47
48 val cl = CList.fromList [1,2,3,4,5,6,7,8,9]
49 val n = CList.length cl
50 val () =
51 case n of
52 NONE => print "NONE\n"
53 | SOME n => print (concat ["SOME ", Int.toString n, "\n"])