🎓 A1Learner
🔍
0 of 45 lessons completed

Composition Patterns

Composition is the building of one function from two smaller functions. Small functions stay easy to test on their own.

andThen runs the left function first

The first function adds two. The second function triples the result.

@main def main(): Unit =
  val addTwo: Int => Int = x => x + 2
  val timesThree: Int => Int = x => x * 3
  val combined = addTwo.andThen(timesThree)
  println(combined(4))

compose runs the argument first

The same two functions run in the opposite order. Tripling happens before adding two.

@main def main(): Unit =
  val addTwo: Int => Int = x => x + 2
  val timesThree: Int => Int = x => x * 3
  val combined = addTwo.compose(timesThree)
  println(combined(4))

Three functions join into one pipeline

Three steps run in written order. The input grows by one, doubles, then grows by ten.

@main def main(): Unit =
  val addOne: Int => Int = x => x + 1
  val double: Int => Int = x => x * 2
  val addTen: Int => Int = x => x + 10
  val combined = addOne.andThen(double).andThen(addTen)
  println(combined(2))

Example

@main def main(): Unit =
  val addFive: Int => Int = x => x + 5
  val double: Int => Int = x => x * 2
  val subtractThree: Int => Int = x => x - 3
  val combined = addFive.andThen(double).andThen(subtractThree)
  println(combined(10))

Key points

  • Pipeline: the result flows from one function into the next function.
  • Use andThen to run the left function before the right function.
  • Compose: a method that runs its argument first and then runs the function it is called on.
  • Order: changing the order of functions can change the final result.
  • Chain: three or more functions can be joined into one pipeline.

In this example, addFive turns 10 into 15. Doubling turns 15 into 30. Subtracting three turns 30 into 27.

Note

creating a combined function does not run either function.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

What does addTwo.andThen(timesThree) give for 5?