Skip to content

Instantly share code, notes, and snippets.

@ahafidi
Created October 16, 2019 12:30
Show Gist options
  • Select an option

  • Save ahafidi/99cc0daee42d81a3177e83ad9c23e2cf to your computer and use it in GitHub Desktop.

Select an option

Save ahafidi/99cc0daee42d81a3177e83ad9c23e2cf to your computer and use it in GitHub Desktop.
import scala.annotation.tailrec
def recursiveSum(f: Int => Int)(a: Int, b: Int): Int = {
if (a > b)
0
else
f(a) + recursiveSum(f)(a + 1, b)
}
def tailRecursiveSum(f: Int => Int)(a: Int, b: Int): Int = {
@tailrec
def loop(curr: Int, acc: Int): Int = {
if (curr > b)
acc
else
loop(curr + 1, acc + f(curr))
}
loop(a, 0)
}
def recursiveProduct(f: Int => Int)(a: Int, b: Int): Int = {
if (a > b)
1
else
f(a) * recursiveProduct(f)(a + 1, b)
}
def tailRecursiveProduct(f: Int => Int)(a: Int, b: Int) = {
@tailrec
def loop(curr: Int, acc: Int): Int = {
if (curr > b)
acc
else
loop(curr + 1, acc * f(curr))
}
loop(a, 1)
}
recursiveSum((x: Int) => x)(1, 10)
tailRecursiveSum((x: Int) => x)(1, 10)
recursiveSum((x: Int) => x * x)(1, 10)
tailRecursiveSum((x: Int) => x * x)(1, 10)
recursiveProduct((x: Int) => x)(1, 4)
tailRecursiveProduct((x: Int) => x)(1, 4)
recursiveProduct((x: Int) => x * x)(1, 4)
tailRecursiveProduct((x: Int) => x * x)(1, 4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment