Higher order functions
Higher order functions
Functions which take functions as parameters
 and/or return functions
Higher order functions
Short summary of first class functions:
val even: (Int => Boolean) = (i: Int) => i % 2 == 0


Same type definition:
def test(numbers: List[Int], f: Int => Boolean) = ...


Call:
test(List(1, 2, 3), (i: Int) => i % 2 == 0)
Higher order functions
def test(numbers: List[Int], f: Int => Boolean) =
  numbers.map(tall => f(tall))


// List[Boolean]
Higher order functions
Functions with several parameters must list them
 in parenthesis:


def test(l: List[String], f: (Int, String) => Boolean)
call-by-value vs. call-by-name
by-value: expressions are evaluated before being
 passed to the function


by-name: expressions evaluated inside function
  nice when computationally expensive
  possible to create nice APIs
call-by-value vs. call-by-name
Example: Logging


def thisTakesTime = {
    println(“Slow computation”)
    “result”
}
logger.debug(thisTakesTime())
call-by-value
def debug(s: String) {
    println(“debug”)
    if (logLevel <= DEBUG) println(s)
}


// Slow computation
// debug
// result
call-by-name
def debug(s: => String) {
    println(“debug”)
    if (logLevel <= DEBUG) println(s)
}


// debug
// Slow computation
// result
BufferedReader reader = null;
try {
  reader = new BufferedReader(new FileReader("f.txt"));
  System.out.println(reader.readLine());
} finally {
  if (reader != null) {
    try {
      reader.close();
    } catch (IOException e) {
      // Exception on close, ignore
    }
  }
}




using(new BufferedReader(new FileReader("f.txt"))) {
    reader => println(reader.readLine())
}
def using[T <: { def close() }, A]
         (closeable: T)
         (f: T => A) = {
  try {
    f(closeable)
  } finally {
    if (closeable != null) {
      try {
        closeable.close()
      }
      catch {
        case e: Exception => // Do something clever!?
      }
    }
  }
}
Tasks (30 min)
Open 'higher-order-functions' project
Tests in scalaexamples.higherorderfunctions
Add @Test to one and one method
Implement missing functions in PersonFilter and
so on.
Follow instructions in code
Make tests pass

2.2 higher order-functions

  • 1.
  • 2.
    Higher order functions Functionswhich take functions as parameters and/or return functions
  • 3.
    Higher order functions Shortsummary of first class functions: val even: (Int => Boolean) = (i: Int) => i % 2 == 0 Same type definition: def test(numbers: List[Int], f: Int => Boolean) = ... Call: test(List(1, 2, 3), (i: Int) => i % 2 == 0)
  • 4.
    Higher order functions deftest(numbers: List[Int], f: Int => Boolean) = numbers.map(tall => f(tall)) // List[Boolean]
  • 5.
    Higher order functions Functionswith several parameters must list them in parenthesis: def test(l: List[String], f: (Int, String) => Boolean)
  • 6.
    call-by-value vs. call-by-name by-value:expressions are evaluated before being passed to the function by-name: expressions evaluated inside function nice when computationally expensive possible to create nice APIs
  • 7.
    call-by-value vs. call-by-name Example:Logging def thisTakesTime = { println(“Slow computation”) “result” } logger.debug(thisTakesTime())
  • 8.
    call-by-value def debug(s: String){ println(“debug”) if (logLevel <= DEBUG) println(s) } // Slow computation // debug // result
  • 9.
    call-by-name def debug(s: =>String) { println(“debug”) if (logLevel <= DEBUG) println(s) } // debug // Slow computation // result
  • 10.
    BufferedReader reader =null; try { reader = new BufferedReader(new FileReader("f.txt")); System.out.println(reader.readLine()); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { // Exception on close, ignore } } } using(new BufferedReader(new FileReader("f.txt"))) { reader => println(reader.readLine()) }
  • 11.
    def using[T <:{ def close() }, A] (closeable: T) (f: T => A) = { try { f(closeable) } finally { if (closeable != null) { try { closeable.close() } catch { case e: Exception => // Do something clever!? } } } }
  • 12.
    Tasks (30 min) Open'higher-order-functions' project Tests in scalaexamples.higherorderfunctions Add @Test to one and one method Implement missing functions in PersonFilter and so on. Follow instructions in code Make tests pass

Editor's Notes

  • #3 Denne siden skal vel bort?
  • #9 Bruke logging eksempelet
  • #10 Logging?