Created
June 11, 2016 11:27
-
-
Save alicanalbayrak/165d36cff2c89420d3eed93b7935a3dc to your computer and use it in GitHub Desktop.
Higher order function scala example
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
/** | |
* Created by alicana on 11/06/2016. | |
*/ | |
object TailRecursiveSum { | |
def square(x: Int): Int = { | |
x * x | |
} | |
def cube(x: Int): Int = { | |
x * x * x | |
} | |
def main(args: Array[String]) { | |
println(sum(x => x,3,5)) | |
println(sum(square,3,5)) | |
println(sum(cube,3,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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment