Function Composition in Scala

package com.vff.lessons

/** Example of composing a function from 2 existing functions. */
object FunctionComposition extends App {

  /* Define the two functions. */
  val less1: Int => Int = _ - 1
  val times2: Int => Int = _ * 2
  val times3: Int => Int = _ * 3

  /* Compose a function from both but note the order: */
  val less1times3 = less1 compose times3

  /* Output result. */
  println("17 times 3 less 1 = " + less1times3(17))
}

Output:

17 times 3 less 1 = 50
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s