2.2 higher order-functions
Upcoming SlideShare
Loading in...5
×
 

2.2 higher order-functions

on

  • 792 views

 

Statistics

Views

Total Views
792
Views on SlideShare
792
Embed Views
0

Actions

Likes
0
Downloads
0
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as OpenOffice

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • Denne siden skal vel bort?
  • Bruke logging eksempelet
  • Logging?

2.2 higher order-functions 2.2 higher order-functions Presentation Transcript

  • Higher order functions
  • Higher order functionsFunctions which take functions as parameters and/or return functions
  • 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)
  • Higher order functionsdef test(numbers: List[Int], f: Int => Boolean) = numbers.map(tall => f(tall))// List[Boolean]
  • Higher order functionsFunctions with several parameters must list them in parenthesis:def test(l: List[String], f: (Int, String) => Boolean)
  • 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
  • call-by-value vs. call-by-nameExample: Loggingdef thisTakesTime = { println(“Slow computation”) “result”}logger.debug(thisTakesTime())
  • call-by-valuedef debug(s: String) { println(“debug”) if (logLevel <= DEBUG) println(s)}// Slow computation// debug// result
  • call-by-namedef 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 projectTests in scalaexamples.higherorderfunctionsAdd @Test to one and one methodImplement missing functions in PersonFilter andso on.Follow instructions in codeMake tests pass