Skip to content

Instantly share code, notes, and snippets.

@ph87
Last active May 1, 2017 17:02
Show Gist options
  • Save ph87/583864ecb944b142de80e6b5eb42df1f to your computer and use it in GitHub Desktop.
Save ph87/583864ecb944b142de80e6b5eb42df1f to your computer and use it in GitHub Desktop.
A map reduce based product currying
object exercise {
def mapReduce(
func: Int=>Int, combine: (Int, Int) => Int, zero: Int
)(a: Int, b: Int): Int = {
if (a > b) zero
else combine(
func(a),
mapReduce(func, combine, zero)(a + 1, b)
)
}
def product(f: Int => Int)(a: Int, b: Int): Int = {
mapReduce(f, (x, y) => x * y, 1)(a, b)
}
def main(args: Array[String]): Unit = {
println(product(x => x * x)(3, 4))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment