2.2 higher order-functions

  • 662 views
Uploaded on

 

More in: Technology , Education
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
662
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
1
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide
  • Denne siden skal vel bort?
  • Bruke logging eksempelet
  • Logging?

Transcript

  • 1. Higher order functions
  • 2. Higher order functionsFunctions which take functions as parameters and/or return functions
  • 3. Higher order functionsShort summary of first class functions:val even: (Int => Boolean) = (i: Int) => i % 2 == 0Same type definition:def test(numbers: List[Int], f: Int => Boolean) = ...Call:test(List(1, 2, 3), (i: Int) => i % 2 == 0)
  • 4. Higher order functionsdef test(numbers: List[Int], f: Int => Boolean) = numbers.map(tall => f(tall))// List[Boolean]
  • 5. Higher order functionsFunctions with several parameters must list them in parenthesis:def test(l: List[String], f: (Int, String) => Boolean)
  • 6. call-by-value vs. call-by-nameby-value: expressions are evaluated before being passed to the functionby-name: expressions evaluated inside function nice when computationally expensive possible to create nice APIs
  • 7. call-by-value vs. call-by-nameExample: Loggingdef thisTakesTime = { println(“Slow computation”) “result”}logger.debug(thisTakesTime())
  • 8. call-by-valuedef debug(s: String) { println(“debug”) if (logLevel <= DEBUG) println(s)}// Slow computation// debug// result
  • 9. call-by-namedef 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 projectTests in scalaexamples.higherorderfunctionsAdd @Test to one and one methodImplement missing functions in PersonFilter andso on.Follow instructions in codeMake tests pass