Last active
June 28, 2017 03:08
-
-
Save dgadiraju/2bce4a83ee55383edf9533107137bce4 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| //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 | |
| } | |
| //anonymous functions defined as variables | |
| val i = (i: Int) => i | |
| val s = (i: Int) => math.pow(i, 2).toInt | |
| val c = (i: Int) => math.pow(i, 3).toInt | |
| sum(i, 1, 100) | |
| sum(s, 1, 10) | |
| sum(c, 1, 3) | |
| //anonymous functions directly passed. | |
| //This is very important and quite often used | |
| sum((i: Int) => i, 1, 100) | |
| sum((s: Int) => s * s, 1, 10) | |
| sum((c: Int) => math.pow(c, 3).toInt, 1, 5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment