Examples
[cc1516.git] / examples / demo / maybe.spl
diff --git a/examples/demo/maybe.spl b/examples/demo/maybe.spl
new file mode 100644 (file)
index 0000000..a4b9416
--- /dev/null
@@ -0,0 +1,44 @@
+//poor mans maybe
+//(1, a) = Just a
+//(0, _) = Nothing
+
+pure(a) :: a -> (Int, a) {
+    return (1, a);
+}
+
+//note, ma is edited by reference!
+fmap(f, ma) :: (a -> b) -> (Int, a) -> (Int, b) {
+    if (ma.fst == 0) { return ma; }
+    else {
+        ma.snd = f(ma.snd);
+        return ma;
+    }
+}
+
+bind(ma, f) :: (Int, a) -> (a -> (Int, b)) -> (Int, b) {
+    if (ma.fst == 0) { return ma; }
+    else {
+        return f(ma.snd);
+    }
+}
+
+main() {
+    
+    var j = pure(True);
+    var f = \b->!b;
+    var n = (0, False); //ugly that we need the additional parameter
+
+    var jf = fmap(\b->!b, j);
+    var nf = fmap(\b->!b, n);
+
+    var fma = \b -> pure(!b);
+
+    var bjf = bind(j, fma); //note is true because ma is passed by reference
+    bar bnf = bind(n, fma);
+
+    print("fmap Just false: ", jf.fst, jf.snd, "\n");
+    print("fmap Nothing: ", nf.fst, "\n");
+
+    print("bind Just True: ", bjf.fst, bjf.snd, "\n");
+    print("bind Nothing: ", bnf.fst, "\n");
+}
\ No newline at end of file