Last active
April 27, 2016 22:58
-
-
Save inakianduaga/d4bf5273daa67a843b39bd77789565a9 to your computer and use it in GitHub Desktop.
Coursera Scala Functional Programming 3rd Week factorial generalization
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
/** | |
* 1. Write a product function that calculates the product of the values of a function for the points on a given interval | |
*/ | |
def product(f: Double => Double)(a: Double, b: Double): Double = { | |
def loop(a: Double, acc: Double): Double = | |
if(a > b) acc else loop(a+1, f(a) * acc) | |
loop(a, 1) | |
} | |
/** | |
* 2. Write factorial in terms of product | |
*/ | |
def factorial(a: Int) = product((a: Double) => a)(1, a) | |
/** | |
* Write a more general function, which generalizes both sum and product | |
*/ | |
def mapReduce(map: Double => Double, reduce: (Double, Double) => Double)(a: Int, b: Int) = { | |
scala.collection.immutable.Range.inclusive(a, b) | |
.map(elem => map(elem)) | |
.reduce((elem, acc) => reduce(elem, acc)) | |
} | |
def factorialAsAMapReduce = mapReduce(a => a, (a, acc) => a * acc)(1, a) | |
def sumAsMapReduce(a: Int, b: Int) = mapReduce(a => a, (a, acc) => a + acc)(a, b) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@deigote Pretty cool how you can think of the factorial function as a simple mapReduce sequence, and the calculation using the mapReduce above is using tail recursion automatically because of reduce.