Last active
August 29, 2015 14:07
-
-
Save oreillyross/5568ca545c25fa845fa3 to your computer and use it in GitHub Desktop.
tail recursive function in scala
This file contains hidden or 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
def factorial(x: Int) = (2 to x).reduceLeft(_ * _) |
This file contains hidden or 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
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