Last active
November 25, 2019 00:36
Recursive factorial function implementation written in WebAssembly Text (WAT)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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