1 (* Copyright (C) 1999-2006 Henry Cejtin, Matthew Fluet, Suresh
2 * Jagannathan, and Stephen Weeks.
4 * MLton is released under a BSD-style license.
5 * See the file MLton-LICENSE for details.
7 (*-------------------------------------------------------------------*)
9 (*-------------------------------------------------------------------*)
11 functor LazyAppendReverse(): APPEND_REVERSE =
14 structure L' = LazyListLength(LazyList)
22 functor IncrementalAppendReverse(): APPEND_REVERSE =
25 structure L' = LazyListLength(LazyList)
29 val appendReverse = L'.appendReverseIncremental
35 functor ExplicitAppendReverse(): APPEND_REVERSE =
38 val {error, ...} = Error.errors("queue", "append-reverse")
40 structure L = StrictList
45 | Cons of 'a * 'a t ref
46 | Rot of 'a t * 'a L.t * 'a L.t
48 fun empty() = List(L.empty())
50 fun destruct(List l) = (case L.destruct l of
52 | SOME(x, l) => SOME(x, List l))
53 | destruct(Cons(x, r)) = (force r ; SOME(x, !r))
54 | destruct _ = error "destruct"
55 and force r = (case !r of
56 Rot lra => r := rot lra
59 (case (destruct l, L.destruct r) of
60 (NONE, SOME(x, _)) => List(L.cons(x, a))
61 | (SOME(x, l), SOME(x', r)) =>
62 Cons(x, ref(Rot(l, r, L.cons(x', a))))
65 fun appendReverse(l, r) = rot(l, r, L.empty())
67 fun isEmpty r = case destruct r of
71 fun length(List l) = L.length l
72 | length(Rot(l, r, a)) = length l + L.length r + L.length a
73 | length(Cons(x, ref r)) = length r + 1
75 fun output(r, sep, outElt, out) =
76 let val print = Out.outputc out
77 fun outputList l = L.output(l, sep, outElt, out)
78 fun output(List l) = outputList l
79 | output(Rot(l, r, a)) = (print "Rot(" ;
86 | output(Cons(x, ref r)) = (outElt(x, out) ;