1 (* Copyright (C) 2009 Matthew Fluet.
2 * Copyright (C) 1999-2006 Henry Cejtin, Matthew Fluet, Suresh
3 * Jagannathan, and Stephen Weeks.
5 * MLton is released under a BSD-style license.
6 * See the file MLton-LICENSE for details.
9 functor Integer (S: INTEGER_STRUCTS): INTEGER =
24 val layout = Layout.str o toString
30 OrderedRing (structure R =
31 RingWithIdentity (structure R = Ring (Int)
36 Relation.lessEqual {< = op <, equals = equals})
40 fun input i = (In.ignoreSpaces i
41 ; (case fromString (In.inputToSpace i) of
45 structure I = EuclideanRing (open R S
46 val metric = toIntInf o abs
47 val monics = Stream.infinite (two, fn n => n + one)
48 val unitEquivalent = abs)
51 fun isEven n = isZero (n mod two)
53 val isOdd = not o isEven
57 fun loop (chars, accum) =
59 fun done () = implode (rev chars @ accum)
62 x1 :: x2 :: x3 :: chars =>
66 | _ => loop (chars, #"," :: x3 :: x2 :: x1 :: accum))
69 in loop (rev (explode (toString n)), [])
73 let val k = max (k, n - k)
74 in prodFromTo {from = add1 k, to = n, term = fn i => i}
78 fun output (n, out) = Out.output (out, toString n)
99 fun least (start: t, stop: t, f: int -> bool): int option =
110 fun 'a fold (start: t, stop: t, a: 'a, f: int * 'a -> 'a): 'a =
112 val _ = Assert.assert ("Integer.fold", fn () => start <= stop + one)
113 fun loop (i: t, a: 'a): 'a =
116 else loop (i + one, f (i, a))
120 fun forall (start: t, stop: t, f: int -> bool): bool =
122 (fn escape => (fold (start, stop, (), fn (i, ()) =>
123 if f i then () else escape false)
126 fun exists (start, stop, f) = not (forall (start, stop, not o f))
128 fun 'a foldDown (start: t, stop: t, a: 'a, f: int * 'a -> 'a): 'a =
130 val _ = Assert.assert ("Integer.foldDown", fn () => start <= stop + one)
131 fun loop (i: t, a: 'a) =
134 else loop (sub1 i, f (i, a))
135 in loop (sub1 stop, a)
138 fun map (start: t, stop: t, f: t -> 'a): 'a list =
139 foldDown (start, stop, [], fn (i, l) => f i :: l)
141 fun for (start: t, stop: t, f: t -> unit): unit =
142 fold (start, stop, (), f o #1)
144 fun forDown (start: t, stop: t, f: t -> unit): unit =
145 foldDown (start, stop, (), f o #1)
147 fun scan (radix, reader) = Int.scan radix reader
149 fun format (i, r) = fmt r i