aboutsummaryrefslogtreecommitdiff
path: root/examples
diff options
context:
space:
mode:
authorJuan J. Martinez <jjm@usebox.net>2022-07-18 12:12:28 +0100
committerJuan J. Martinez <jjm@usebox.net>2022-07-18 12:12:28 +0100
commitb6b68929a7efb19962795211c58d52dd08249235 (patch)
treed3f3307382626d39f4b483db6d2a5b53acc28ab6 /examples
parentf7686379eb2fdc740b76a714f80435b71be9c24c (diff)
downloadmicro-lang-b6b68929a7efb19962795211c58d52dd08249235.tar.gz
micro-lang-b6b68929a7efb19962795211c58d52dd08249235.zip
Added examples
Diffstat (limited to 'examples')
-rw-r--r--examples/fact.micro15
-rw-r--r--examples/fib.micro18
-rw-r--r--examples/safediv.micro18
-rw-r--r--examples/wilsonp.micro34
4 files changed, 85 insertions, 0 deletions
diff --git a/examples/fact.micro b/examples/fact.micro
new file mode 100644
index 0000000..29b73c3
--- /dev/null
+++ b/examples/fact.micro
@@ -0,0 +1,15 @@
+//
+// Factorial, with recursive tail call optimization
+//
+
+def fact(n number, acc number) number {
+ if n == 1 {
+ return acc;
+ } else {
+ return fact(n - 1, acc * n);
+ }
+}
+
+
+println("fact 20: ", fact(20, 1));
+
diff --git a/examples/fib.micro b/examples/fib.micro
new file mode 100644
index 0000000..efd7517
--- /dev/null
+++ b/examples/fib.micro
@@ -0,0 +1,18 @@
+//
+// Using recursive tail call optimizations
+//
+
+def fib(n number, acc1 number, acc2 number) number {
+ if n == 0 {
+ return acc1;
+ } else {
+ if n == 1 {
+ return acc2;
+ } else {
+ return fib(n - 1, acc2, acc1 + acc2);
+ }
+ }
+}
+
+println("fib 90: ", fib(90, 0, 1));
+
diff --git a/examples/safediv.micro b/examples/safediv.micro
new file mode 100644
index 0000000..b13b62c
--- /dev/null
+++ b/examples/safediv.micro
@@ -0,0 +1,18 @@
+//
+// Example of error handling
+//
+
+def safeDiv(a number, b number) number {
+ if b == 0 {
+ // error!
+ return !? 0;
+ }
+
+ return a / b;
+}
+
+var result number;
+
+if ? (result = safeDiv(1, 0)) {
+ println("error in safeDiv");
+}
diff --git a/examples/wilsonp.micro b/examples/wilsonp.micro
new file mode 100644
index 0000000..9bc626f
--- /dev/null
+++ b/examples/wilsonp.micro
@@ -0,0 +1,34 @@
+//
+// Show prime numbers using the Wilson theorem: https://en.wikipedia.org/wiki/Wilson%27s_theorem#Primality_tests
+//
+// Also using a recursive function for the loops
+//
+
+def loop(from number, to number, fn func (number) bool) {
+ if from > to {
+ return;
+ }
+ if !fn(from) {
+ return;
+ }
+ return loop(from + 1, to, fn);
+}
+
+def wilsonPrime(n number) bool {
+ var acc number = 1;
+ def fact(i number) bool {
+ acc = (acc * i) % n;
+ return acc != 0;
+ }
+
+ loop(2, n - 1, fact);
+
+ if acc == n - 1 {
+ println(n, " is prime");
+ }
+
+ return true;
+}
+
+loop(2, 100, wilsonPrime);
+