Exercise 5.2.3 Write factorial in terms of product.
This file contains 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
object Factorial { | |
def product(f: Int => Int)(a: Int, b:Int): Int = { | |
if (a > b) 1 else f(a) * product(f)(a + 1, b) | |
} | |
def factorial(n: Int): Int = { | |
product(x => x)(1, n) | |
} | |
def main(args: Array[String]) { | |
println("Factorial of 6 is: " + factorial(6)) | |
} | |
} |
No comments:
Post a Comment