Skip to content

Instantly share code, notes, and snippets.

@mgthomas99
Last active November 25, 2019 00:36
Show Gist options
  • Save mgthomas99/473d77792696361bf33eeadd74dec41b to your computer and use it in GitHub Desktop.
Save mgthomas99/473d77792696361bf33eeadd74dec41b to your computer and use it in GitHub Desktop.
Recursive factorial function implementation written in WebAssembly Text (WAT)
(module
;;; Calculates and returns the factorial of the first parameter using
;;; recursion.
;;; @param {i32} $x
;;; The value to calculate the factorial of.
;;; @return {i32}
;;; The factorial of `$x`.
(func $fact (param $x i32) (result i32)
(get_local $x)
(i32.const 1)
(if (result i32) (i32.le_s)
;; If `$x <= 1` then return `$x`.
(then
(get_local $x)
)
;; Else, return `$x * fact($x - 1)`.
(else
(get_local $x)
(i32.const 1)
(i32.sub)
(call $fact)
(get_local $x)
(i32.mul)
)
)
)
;; Export the `fact` function so that it can be imported into another script.
(export "fact" (func $fact))
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment