Skip to content

Instantly share code, notes, and snippets.

@mgthomas99
Last active November 25, 2019 00:36
Show Gist options
  • Select an option

  • Save mgthomas99/473d77792696361bf33eeadd74dec41b to your computer and use it in GitHub Desktop.

Select an option

Save mgthomas99/473d77792696361bf33eeadd74dec41b to your computer and use it in GitHub Desktop.

Revisions

  1. mgthomas99 renamed this gist Mar 19, 2019. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. mgthomas99 created this gist Mar 15, 2019.
    33 changes: 33 additions & 0 deletions fact.wat
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,33 @@

    (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))
    )