Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- object CumulativeOps {
- def cumSum[A](xs: Seq[A])(implicit num: Numeric[A]): Seq[A] = {
- xs.tail.scanLeft(xs.head)(num.plus)
- }
- def cumDiff[A](xs: Seq[A])(implicit num: Numeric[A]): Seq[A] = {
- val total = xs.sum
- xs.scanLeft(total)(num.minus).dropRight(1)
- }
- def cumMultiplication[A](xs: Seq[A])(implicit num: Numeric[A]): Seq[A] = {
- xs.tail.scanLeft(xs.head)(num.times)
- }
- }
- class CumulativeOpsTest extends WordSpec with Matchers {
- "CumulativeOps" should {
- "calculate cumulative sum of Ints" in {
- CumulativeOps.cumSum(Vector(1, 2, 4, 7, 3, 4)) should
- contain theSameElementsInOrderAs (Seq(1, 3, 7, 14, 17, 21))
- }
- "calculate cumulative sum of Doubles" in {
- CumulativeOps.cumSum(Vector(1.25, 2, 4.25, 7.5, 3.25, 4.75)) should
- contain theSameElementsInOrderAs (Vector(1.25, 3.25, 7.5, 15.0, 18.25, 23.0))
- }
- "calculate cumulative diff of Ints" in {
- CumulativeOps.cumDiff(Vector(1, 2, 4, 7, 3, 4)) should
- contain theSameElementsInOrderAs (Vector(21, 20, 18, 14, 7, 4))
- }
- "calculate cumulative diff of Doubles" in {
- CumulativeOps.cumDiff(Vector(1.25, 2.5, 4, 7.25, 3, 4)) should
- contain theSameElementsInOrderAs (Vector(22.0, 20.75, 18.25, 14.25, 7.0, 4.0))
- }
- "calculate cumulative multiplication of Ints" in {
- CumulativeOps.cumMultiplication((List(2, 3, 7, 14, 17, 21))) should
- contain theSameElementsInOrderAs (Vector(2, 6, 42, 588, 9996, 209916))
- }
- "calculate cumulative multiplication of Doubles" in {
- CumulativeOps.cumMultiplication((List(0.99, 0.83, 0.74, 0.5, 0.5, 0.5))) should
- contain theSameElementsInOrderAs (Vector(0.99, 0.8217, 0.608058, 0.304029, 0.1520145, 0.07600725))
- }
- }
- }
Add Comment
Please, Sign In to add comment