From b6b68929a7efb19962795211c58d52dd08249235 Mon Sep 17 00:00:00 2001 From: "Juan J. Martinez" Date: Mon, 18 Jul 2022 12:12:28 +0100 Subject: Added examples --- examples/fact.micro | 15 +++++++++++++++ examples/fib.micro | 18 ++++++++++++++++++ examples/safediv.micro | 18 ++++++++++++++++++ examples/wilsonp.micro | 34 ++++++++++++++++++++++++++++++++++ 4 files changed, 85 insertions(+) create mode 100644 examples/fact.micro create mode 100644 examples/fib.micro create mode 100644 examples/safediv.micro create mode 100644 examples/wilsonp.micro (limited to 'examples') 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); + -- cgit v1.2.3