typestar

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

  1. (func $fact (export "factorial") ...) binds both names at once.
  2. The base case returns 1 through the typed if.
  3. The else multiplies by call $fact of n minus one.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Calls, step 14 of 28 in Language basics.

← Previous Next →

Recursion in other languages