Skip to content

Instantly share code, notes, and snippets.

@MaxySpark
Created March 25, 2020 18:50
Show Gist options
  • Save MaxySpark/12a64a80418338cc7fbaaabdc455f7a0 to your computer and use it in GitHub Desktop.
Save MaxySpark/12a64a80418338cc7fbaaabdc455f7a0 to your computer and use it in GitHub Desktop.
def factorial(n: Int): Int = {
def loop(acc: Int, n: Int): Int =
if (n == 0) acc
else loop(acc * n, n-1)
loop(1, n)
}
factorial(5)
def sum(f: Int => Int, a: Int, b: Int): Int = {
def loop(a: Int, acc: Int): Int = {
if (a > b) acc
else loop(a + 1, f(a) + acc)
}
loop(a, 0)
}
sum(x => x*x, 3,5)
def product(f: Int => Int) (a: Int, b: Int): Int =
if (a > b) 1
else f(a) * product(f)(a + 1, b)
product(x => x * x)(3, 4)
def fact(n: Int) = product(x => x)(1, n)
fact(5)
def mapReduce(f: Int => Int, combine: (Int, Int) => Int, zero: Int) (a: Int, b: Int) : Int=
if (a > b) zero
else combine(f(a), mapReduce(f, combine, zero)(a+1, b))
def productMapReduce(f: Int => Int)(a: Int, b: Int): Int = mapReduce(f, (x, y) => x * y, 1)(a, b)
productMapReduce(x => x * x)(3, 4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment