chiark / gitweb /
test/: Add a simple rational-number class.
[sod] / test / rat.sod
1 /* -*-sod-*- */
2
3 code c: includes {
4 #include <assert.h>
5 #include <stdio.h>
6
7 #include "rat.h"
8 }
9
10 code h: includes {
11 #include "sod.h"
12 }
13
14 typename FILE;
15
16 code c: early_user {
17   static int gcd(int x, int y)
18   {
19     int t;
20     if (x < 0) x = -x;
21     if (y < 0) y = -y;
22     while (y) { t = x%y; x = y; y = t; }
23     return (x);
24   }
25 }
26
27 [nick = rat, link = SodObject]
28 class Rational: SodObject {
29   int num, den;
30   initarg int num = 0, den = 1;
31   init {
32     int g;
33     assert(den);
34     g = gcd(num, den);
35     me->rat.num = num/g;
36     me->rat.den = den/g;
37   }
38
39   void print(FILE *fp) { fprintf(fp, "%d/%d\n", me->rat.num, me->rat.den); }
40 }
41
42 code c: user {
43   int main(void)
44   {
45     SOD_DECL(Rational, r0, KWARGS(K(den, 9)));
46     SOD_DECL(Rational, r1, KWARGS(K(num, 6)));
47     SOD_DECL(Rational, r2, KWARGS(K(num, 6) K(den, 9)));
48     Rational_print(r0, stdout);
49     Rational_print(r1, stdout);
50     Rational_print(r2, stdout);
51     return (0);
52   }
53 }