reset password
Author Message
rabbott
Posts: 1649
Posted 22:00 Oct 08, 2013 |

What if you wanted to define a function that takes two functions as its argument and returns the function which is the composition of the two.

  def compose(f: Int => Int, g: Int => Int): Int => Int = {
       // This defines the composition function
       def f_of_g_of_x(x: Int): Int = f(g(x))
       // This returns it as the value of the compose function
       f_of_g_of_x
  }                                                              //> compose: (f: Int => Int, g: Int => Int)Int => Int

  def add1(x: Int): Int = x + 1                   //> add1: (x: Int)Int
  def double(x: Int): Int = x * 2                 //> double: (x: Int)Int

  val doubleAndAdd1 = compose(add1, double)       //> doubleAndAdd1  : Int => Int = <function1>

  doubleAndAdd1(5)                                //> res7: Int = 11