Created
October 16, 2019 12:30
-
-
Save ahafidi/99cc0daee42d81a3177e83ad9c23e2cf 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
| 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