about summary refs log tree commit diff
diff options
context:
space:
mode:
authorBaitinq <[email protected]>2025-03-09 12:12:10 +0100
committerBaitinq <[email protected]>2025-03-09 12:12:10 +0100
commit13009c9d92756ecbf38d2ac9b9e85a59c92fc8b9 (patch)
tree594184a7181b6604015108521b774235f0f1ab71
parentCodegen: Fix bug with if statements inside while loops (diff)
downloadinterpreter-13009c9d92756ecbf38d2ac9b9e85a59c92fc8b9.tar.gz
interpreter-13009c9d92756ecbf38d2ac9b9e85a59c92fc8b9.tar.bz2
interpreter-13009c9d92756ecbf38d2ac9b9e85a59c92fc8b9.zip
Examples: Add new more complex examples
-rw-r--r--examples/12.src42
-rw-r--r--examples/13.src31
2 files changed, 67 insertions, 6 deletions
diff --git a/examples/12.src b/examples/12.src
index 1bff280..a680efa 100644
--- a/examples/12.src
+++ b/examples/12.src
@@ -1,8 +1,38 @@
-let print_int = (n: i64) => i64 {
-	print(n);
-	return n;
-};
+let main = () => i64 {
+    let factorial = (n: i64) => i64 {
+        let f = (acc: i64, n: i64) => i64 {
+            if n == 0 {
+                return acc;
+            };
+            return f(acc * n, n - 1);
+        };
+        return f(1, n);
+    };
+
+    let is_even = (n: i64) => bool {
+        if n % 2 == 0 {
+            return true;
+        };
+        return false;
+    };
+
+    let sum_if = (predicate: (i64) => bool, limit: i64) => i64 {
+        let sum = 0;
+        let i = 0;
+        while i < limit {
+            if predicate(i) {
+                sum = sum + i;
+            };
+            i = i + 1;
+        };
+        return sum;
+    };
+
+    let fact_val = factorial(6);
+    print(fact_val);
+
+    let even_sum = sum_if(is_even, 20);
+    print(even_sum);
 
-let main = (argc: i64) => i64 {
-	return print_int(argc);
+    return 0;
 };
diff --git a/examples/13.src b/examples/13.src
new file mode 100644
index 0000000..eeb5b32
--- /dev/null
+++ b/examples/13.src
@@ -0,0 +1,31 @@
+let main = () => i64 {
+    /* Iterative Fibonacci using while loop. */
+    let fibonacci_iter = (n: i64) => i64 {
+        let a = 0;
+        let b = 1;
+        let i = 0;
+        while i < n {
+            let temp = b;
+            b = a + b;
+            a = temp;
+            i = i + 1;
+        };
+        return a;
+    };
+
+    /* Recursive GCD using Euclid's algorithm. */
+    let gcd = (a: i64, b: i64) => i64 {
+        if b == 0 {
+            return a;
+        };
+        return gcd(b, a % b);
+    };
+
+    let fib_val = fibonacci_iter(10);
+    print(fib_val);
+
+    let gcd_val = gcd(48, 18);
+    print(gcd_val);
+
+    return 0;
+};