diff options
author | Jérémy Zurcher <jeremy@asynk.ch> | 2013-04-03 22:18:48 +0200 |
---|---|---|
committer | Jérémy Zurcher <jeremy@asynk.ch> | 2016-11-10 18:03:22 +0100 |
commit | 476583c90a47cad62f992ab0b845ebf2897cb47d (patch) | |
tree | c3742b376e852cc34b3bcfe052fd7aa1acbc09f5 /Scala/sandbox/curry.scala | |
parent | 545c03ac4981737594d7638b7a925d1881a74cdc (diff) | |
download | coursera-476583c90a47cad62f992ab0b845ebf2897cb47d.zip coursera-476583c90a47cad62f992ab0b845ebf2897cb47d.tar.gz |
Scala : cleanup, Scala : add sumCurry
Diffstat (limited to 'Scala/sandbox/curry.scala')
-rw-r--r-- | Scala/sandbox/curry.scala | 30 |
1 files changed, 30 insertions, 0 deletions
diff --git a/Scala/sandbox/curry.scala b/Scala/sandbox/curry.scala new file mode 100644 index 0000000..910de62 --- /dev/null +++ b/Scala/sandbox/curry.scala @@ -0,0 +1,30 @@ + +object Curry { + + // high order function + def sum(f: Int => Int, a: Int, b: Int) = { + def loop(a: Int, acc: Int): Int = + if (a > b) acc + else loop(a + 1, f(a) + acc) + loop(a, 0) + } + + // curry version: this function return an (Int, Int) => Int function + def sumCurry(f: Int => Int): (Int, Int) => Int = { + def sumF(a: Int, b: Int): Int = + if (a > b) 0 + else f(a) + sumF(a + 1, b) + sumF + } + + def sumInts = sumCurry(x => x) + def sumCubes = sumCurry(x => x * x) + + def run = { + println("Curry") + println(sum(x => x * x, 3, 5)) + println(sumInts(3, 5)) + println(sumCubes(3, 5)) + } + +} |