Created
October 3, 2013 06:57
-
-
Save cultofmetatron/6806097 to your computer and use it in GitHub Desktop.
rangeLoop scala function
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
object Foo { | |
def factorial(n:Int): Int = { | |
def factorialIter( n: Int , acc: Int, initial: Int) : Int = { | |
if (initial == n) | |
acc * initial | |
else | |
factorialIter(n, acc * initial, initial + 1) | |
} | |
factorialIter(n, 1, 1); | |
} | |
def factorial2(n:Int): Int = product(x => x)(1, n); | |
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) | |
} | |
def rangeLoop(f:(Int, Int) => Int, acc:Int)(g: Int => Int)(a:Int, b:Int) = { | |
def loop(a:Int, acc:Int):Int = { | |
if (a > b) acc | |
else loop(a + 1, f(g(a), acc)) | |
} | |
loop(a, acc) | |
} | |
/* write a product function that calculates | |
* the values of a function for points on an interval? | |
*/ | |
def product(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, 1) | |
} | |
def product2(f: Int => Int)(a:Int, b:Int): Int = | |
rangeLoop((x, y) => x * y, 1)(f)(a, b) | |
def main() = { | |
sum(x=> x * x, 3, 5) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment