Examples
loops.mul
Greatest common divisor by Euclid's algorithm: a and b change on every iteration, so the loop header takes both as block parameters.
Source
examples/loops.mul is stored in the compact layout, as AI agents write it: a space only between two words, no other whitespace. The page lays it out for reading; the Compact button shows the stored text, and Copy always copies it.
module demo.loops
// Greatest common divisor by Euclid's algorithm: `a` and `b` change on
// every iteration, so the loop header takes both as block parameters.
fn gcd(a:i32,b:i32)->i32{var x=a var y=b while y!=0{let rest=x%y x=y y=rest}return x}
// Counts the primes below `limit` with nested loops; the inner loop ends
// early through its condition once a divisor is found.
fn primesBelow(limit:i32)->i32{var count=0 var n=2 while n<limit{var d=2 var prime=true while prime&&d*d<=n{if n%d==0{prime=false}d=d+1}if prime{count=count+1}n=n+1}return count}pub fn main()->i32{return gcd(1071,462)*1000+primesBelow(100)}
Verified IR
What mul ir prints after the verifier has accepted the program.
module demo.loops
fn @gcd(%0: i32, %1: i32) -> i32 {
b0:
jump b1(%0, %1)
b1(%2: i32, %3: i32):
%4 = const.i32 0
%5 = ne.i32 %3, %4
branch %5, b2, b3
b2:
%6 = rem.i32 %2, %3
jump b1(%3, %6)
b3:
return %2
}
fn @primesBelow(%0: i32) -> i32 {
b0:
%1 = const.i32 0
%2 = const.i32 2
jump b1(%1, %2)
b1(%3: i32, %4: i32):
%5 = lt.i32 %4, %0
branch %5, b2, b3
b2:
%6 = const.i32 2
%7 = const.bool true
jump b4(%6, %7)
b3:
return %3
b4(%8: i32, %9: bool):
branch %9, b5, b6(%9)
b5:
%10 = mul.i32 %8, %8
%11 = le.i32 %10, %4
jump b6(%11)
b6(%12: bool):
branch %12, b7, b8
b7:
%13 = rem.i32 %4, %8
%14 = const.i32 0
%15 = eq.i32 %13, %14
branch %15, b9, b10
b8:
branch %9, b12, b13
b9:
%16 = const.bool false
jump b11(%16)
b10:
jump b11(%9)
b11(%17: bool):
%18 = const.i32 1
%19 = add.i32 %8, %18
jump b4(%19, %17)
b12:
%20 = const.i32 1
%21 = add.i32 %3, %20
jump b14(%21)
b13:
jump b14(%3)
b14(%22: i32):
%23 = const.i32 1
%24 = add.i32 %4, %23
jump b1(%22, %24)
}
fn @main() -> i32 {
b0:
%0 = const.i32 1071
%1 = const.i32 462
%2 = call.i32 @gcd(%0, %1)
%3 = const.i32 1000
%4 = mul.i32 %2, %3
%5 = const.i32 100
%6 = call.i32 @primesBelow(%5)
%7 = add.i32 %4, %6
return %7
}
Run
The value main returns is the exit code of the process.
$ mul run examples/loops.mul; echo "exit code $?"
exit code 33