Debian Codegraph @

examples/prism-sml.html

raw symbols SCIP
1 <h2>Full example</h2>
2 <pre><code>(* source: https://github.com/HarrisonGrodin/ml-numbers/blob/ba35c763092052e391871edf224f17474c6231b1/src/Rational.sml *)
3
4 structure Rational :> RATIONAL =
5 struct
6 type t = int * int (* (a,b) invariant: a,b coprime; b nonnegative *)
7
8 local
9 val rec gcd = fn
10 (m,0) => m
11 | (m,n) => gcd (n, m mod n)
12 in
13 infix 8 //
14 val op // = fn (x,y) => (
15 let
16 val gcd = gcd (x,y)
17 in
18 (x div gcd, y div gcd)
19 end
20 )
21 end
22
23 val show = Fn.id
24
25 val zero = (0,1)
26 val one = (1,1)
27
28 val eq : t * t -> bool = (op =)
29 val compare = fn ((a,b),(x,y)) => Int.compare (a * y, b * x)
30 val toString = fn (x,y) => Int.toString x ^ " // " ^ Int.toString y
31 val percent =
32 Fn.curry (Fn.flip (op ^)) "%"
33 o Int.toString
34 o (fn (a,b) => (100 * a) div b)
35
36 val op + = fn ((a,b),(x,y)) => (a * y + b * x) // (b * y)
37 val ~ = fn (a,b) => (~a,b)
38 val op - = fn (r1,r2) => r1 + ~r2
39
40 val op * = fn ((a,b),(x,y)) => (a * x) // (b * y)
41 val inv = Fn.flip (op //)
42 val op / = fn (r1,r2) => r1 * inv r2
43 end</code></pre>