Import Upstream version 20180207
[hcoop/debian/mlton.git] / lib / mlton / basic / ordered-ring.fun
1 (* Copyright (C) 1999-2006 Henry Cejtin, Matthew Fluet, Suresh
2 * Jagannathan, and Stephen Weeks.
3 *
4 * MLton is released under a BSD-style license.
5 * See the file MLton-LICENSE for details.
6 *)
7
8 functor OrderedRing(S: ORDERED_RING_STRUCTS):> ORDERED_RING where type t = S.t =
9 struct
10
11 open S
12 structure U = Ring(S)
13 open U
14
15 fun isPositive n = n > zero
16
17 fun isNegative n = n < zero
18
19 fun abs n = if isPositive n then n else ~ n
20
21 fun foldl(from, to, b, f) =
22 let fun fold(n, a) = if n > to then a
23 else fold(add1 n, f(a,n))
24 in fold(from, b)
25 end
26
27 local
28 fun abs (combine, base) {from, to, term} =
29 foldl(from, to, base, fn (a, i) => combine(a, term i))
30 in
31 val sumFromTo = abs(op +, zero)
32 val prodFromTo = abs(op *, one)
33 end
34
35 fun factorial n = prodFromTo{from = one, to = n, term = fn i => i}
36
37 fun max(m, n) = if m > n then m else n
38
39 fun min(m, n) = if m < n then m else n
40
41 end