Skip to content

Instantly share code, notes, and snippets.

@hpcx82
Created June 5, 2012 13:20
Show Gist options
  • Save hpcx82/2874939 to your computer and use it in GitHub Desktop.
Save hpcx82/2874939 to your computer and use it in GitHub Desktop.
factorial
object factorialTest extends App
{
def factorial(n: Int): Int =
{
if(n == 0) 1 else n * factorial(n-1)
}
println(factorial(3))
println(factorial(10))
}
object factorialTest extends App
{
def factorialRecur(n: Int, acc: Int): Int =
{
if(n == 0) acc else factorialRecur(n-1, acc*n)
}
def factorial(n: Int) = factorialRecur(n, 1)
println(factorial(3))
println(factorial(10))
}
@hpcx82
Copy link
Author

hpcx82 commented Jun 5, 2012

To transform a non-tail recursion to tail recursion, just use a parameter to hold and accumulate the results.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment