Skip to content

Instantly share code, notes, and snippets.

@dgadiraju
Last active September 14, 2017 14:51
Show Gist options
  • Select an option

  • Save dgadiraju/b76e405c56f00648046d367ce9f37c69 to your computer and use it in GitHub Desktop.

Select an option

Save dgadiraju/b76e405c56f00648046d367ce9f37c69 to your computer and use it in GitHub Desktop.
//recursive
def sum(f: Int => Int, a: Int, b: Int): Int = {
if(a > b) 0 else f(a) + sum(f, a + 1, b)
}
//non recursive
def sum(f: Int => Int, a: Int, b: Int): Int = {
var res = 0
for(ele <- a to b by 1)
res = res + f(ele)
res
}
def id(i: Int) = i
def sqr(i: Int) = math.pow(i, 2).toInt
def cube(i: Int) = math.pow(i, 3).toInt
sum(id, 1, 10)
sum(sqr, 1, 5)
sum(cube, 1, 4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment