Skip to content

Instantly share code, notes, and snippets.

@oreillyross
Last active August 29, 2015 14:07
Show Gist options
  • Save oreillyross/5568ca545c25fa845fa3 to your computer and use it in GitHub Desktop.
Save oreillyross/5568ca545c25fa845fa3 to your computer and use it in GitHub Desktop.
tail recursive function in scala
def factorial(x: Int) = (2 to x).reduceLeft(_ * _)
def factorial(i: BigInt): BigInt = {
def fact(i: BigInt, accum: BigInt): BigInt = i match {
case _ if i == 1 => accum
case _ => fact(i - 1, i * accum)
}
fact(i, 1)
}
// test the function with a for loop implementation
for (i <- 1 to 10)
println(format("%s: %s", i, factorial(i)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment