Created
March 16, 2015 06:18
-
-
Save sergiilagutin/32f9f80560d099dacf6d to your computer and use it in GitHub Desktop.
Simple reduce
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
import scala.annotation.tailrec | |
def sum(numbers: Seq[Int]): Int = | |
loopRight(numbers, 0, _ + _) | |
def product(numbers: Seq[Int]): Int = | |
loopRight(numbers, 1, _ * _) | |
def sumTail(numbers: Seq[Int]): Int = | |
loopLeft(numbers, 0, (acc, i) => acc + i) | |
def productTail(numbers: Seq[Int]): Int = | |
loopLeft(numbers, 1, _ * _) | |
def loopLeft(numbers: Seq[Int], init: Int, f: ((Int, Int) => Int)) = { | |
@tailrec | |
def loop(acc: Int, seq: Seq[Int]): Int = | |
if (seq.isEmpty) acc | |
else loop(f(acc, seq.head), seq.tail) | |
loop(init, numbers) | |
} | |
def loopRight(numbers: Seq[Int], init: Int, f: ((Int, Int) => Int)): Int = | |
if (numbers.isEmpty) init | |
else f(numbers.head, loopRight(numbers.tail, init, f)) | |
sum((1 to 10).toList) | |
product((1 to 5).toList) | |
sumTail((1 to 10).toList) | |
productTail((1 to 5).toList) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment