Skip to content

Instantly share code, notes, and snippets.

@tsmacdonald
Last active August 29, 2015 14:00
Show Gist options
  • Save tsmacdonald/11360648 to your computer and use it in GitHub Desktop.
Save tsmacdonald/11360648 to your computer and use it in GitHub Desktop.
(* Iterative approach; O(1) memory *)
fun factorial n =
let
val tally = ref 1
val i = ref 1
in
while !i < n do
tally := !tally * i
i := !i + 1;
end;
(* Naive recursion; O(n) memory *)
fun factorial 0 = 1
| factorial n = n * factorial(n - 1)
(* Tail recursion; O(1) memory *)
fun factorial n =
let
fun factorial_iter i tally =
if i > n then
tally
else
factorial_iter(i + 1)(tally * i)
in
factorial_iter 1 1
end;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment