chiark / gitweb /
test/: Add a simple rational-number class.
authorMark Wooding <mdw@distorted.org.uk>
Tue, 15 May 2018 10:44:56 +0000 (11:44 +0100)
committerMark Wooding <mdw@distorted.org.uk>
Fri, 8 Jun 2018 19:08:03 +0000 (20:08 +0100)
This found a surprising number of bugs.  I wasn't even intending for it
to be a test, but it seems to work well as one.

test/Makefile.am
test/rat.ref [new file with mode: 0644]
test/rat.sod [new file with mode: 0644]

index 5c4d59d..de5b634 100644 (file)
@@ -58,4 +58,13 @@ check-local:: kwtest kwtest.ref
        ./kwtest >kwtest.out
        diff -u $(srcdir)/kwtest.ref kwtest.out
 
+check_PROGRAMS         += rat
+
+EXTRA_DIST             += rat.sod rat.ref
+nodist_rat_SOURCES      = rat.c rat.h
+BUILT_SOURCES          += $(nodist_rat_SOURCES)
+check-local:: rat rat.ref
+       ./rat >rat.out
+       diff -u $(srcdir)/rat.ref rat.out
+
 ###----- That's all, folks --------------------------------------------------
diff --git a/test/rat.ref b/test/rat.ref
new file mode 100644 (file)
index 0000000..2f3b0f6
--- /dev/null
@@ -0,0 +1,3 @@
+0/1
+6/1
+2/3
diff --git a/test/rat.sod b/test/rat.sod
new file mode 100644 (file)
index 0000000..178e896
--- /dev/null
@@ -0,0 +1,53 @@
+/* -*-sod-*- */
+
+code c: includes {
+#include <assert.h>
+#include <stdio.h>
+
+#include "rat.h"
+}
+
+code h: includes {
+#include "sod.h"
+}
+
+typename FILE;
+
+code c: early_user {
+  static int gcd(int x, int y)
+  {
+    int t;
+    if (x < 0) x = -x;
+    if (y < 0) y = -y;
+    while (y) { t = x%y; x = y; y = t; }
+    return (x);
+  }
+}
+
+[nick = rat, link = SodObject]
+class Rational: SodObject {
+  int num, den;
+  initarg int num = 0, den = 1;
+  init {
+    int g;
+    assert(den);
+    g = gcd(num, den);
+    me->rat.num = num/g;
+    me->rat.den = den/g;
+  }
+
+  void print(FILE *fp) { fprintf(fp, "%d/%d\n", me->rat.num, me->rat.den); }
+}
+
+code c: user {
+  int main(void)
+  {
+    SOD_DECL(Rational, r0, KWARGS(K(den, 9)));
+    SOD_DECL(Rational, r1, KWARGS(K(num, 6)));
+    SOD_DECL(Rational, r2, KWARGS(K(num, 6) K(den, 9)));
+    Rational_print(r0, stdout);
+    Rational_print(r1, stdout);
+    Rational_print(r2, stdout);
+    return (0);
+  }
+}