Recursion in WebAssembly
A function calls itself by its own $name.
(module
;; A function may call itself; the stack is the call stack.
(func $fact (export "factorial") (param $n i32) (result i32)
(if (result i32)
(i32.le_s (local.get $n) (i32.const 1))
(then (i32.const 1))
(else
(i32.mul
(local.get $n)
(call $fact
(i32.sub (local.get $n) (i32.const 1))))))))
How it works
(func $fact (export "factorial") ...)binds both names at once.- The base case returns 1 through the typed if.
- The else multiplies by
call $factof n minus one.
Keywords and builtins used here
callelseexportfunci32ifmoduleparamresultthen
The run, in numbers
- Lines
- 11
- Characters to type
- 293
- Tokens
- 73
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 67 seconds.
Step 2 of 3 in Calls, step 14 of 28 in Language basics.