ðŸŽ‰ Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io ðŸŽ‰

billwanjohi's solution

to Accumulate in the Scala Track

Published at Feb 18 2019 · 0 comments
Instructions
Test suite
Solution

Implement the `accumulate` operation, which, given a collection and an operation to perform on each element of the collection, returns a new collection containing the result of applying that operation to each element of the input collection.

Given the collection of numbers:

• 1, 2, 3, 4, 5

And the operation:

• square a number (`x => x * x`)

Your code should be able to produce the collection of squares:

• 1, 4, 9, 16, 25

Check out the test suite to see the expected function signature.

Restrictions

Keep your hands off the map, flatMap and for comprehension functionality provided by the standard library! Solve this one yourself using other basic tools instead.

The Scala exercises assume an SBT project scheme. The exercise solution source should be placed within the exercise directory/src/main/scala. The exercise unit tests can be found within the exercise directory/src/test/scala.

To run the tests simply run the command `sbt test` in the exercise directory.

For more detailed info about the Scala track see the help page.

Source

Conversation with James Edward Gray II https://twitter.com/jeg2

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

AccumulateTest.scala

``````import org.scalatest.{Matchers, FlatSpec}

/** @version created manually **/
class AccumulateTest extends FlatSpec with Matchers {

it should "allow empty accumulation" in {
val accumulate = new Accumulate
val accumulation = accumulate.accumulate[Int, Int](x => x * x, List.empty)
accumulation should be (List.empty)
}

it should "accumulate squares" in {
pending
val accumulate = new Accumulate
val accumulation = accumulate.accumulate[Int, Int](x => x * x, List(1, 2, 3))
accumulation should be (List(1, 4, 9))
}

it should "accumulate upcases" in {
pending
val accumulate = new Accumulate
val accumulation = accumulate.accumulate[String, String](_.map(_.toUpper), List("hello", "world"))
accumulation should be (List("HELLO", "WORLD"))
}

it should "accumulate reversed strings" in {
pending
val accumulate = new Accumulate
val accumulation = accumulate.accumulate[String, String](_.reverse, List("eht", "kciuq", "nworb", "xof", "cte"))
accumulation should be (List("the", "quick", "brown", "fox", "etc"))
}

it should "allow different return type" in {
pending
val accumulate = new Accumulate
val accumulation = accumulate.accumulate[Int, String](_.toString, List(1, 2, 3))
accumulation should be (List("1", "2", "3"))
}
}``````
``````class Accumulate {
def accumulate[A, B](f: (A) => B, list: List[A]): List[B] =
list.foldLeft(List[B]()) ((acc, item) => acc :+ f(item))
}``````