1.4 first class-functions
Upcoming SlideShare
Loading in...5
×
 

1.4 first class-functions

on

  • 200 views

 

Statistics

Views

Total Views
200
Views on SlideShare
200
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
  • Vanskelig å forklare foldleft med flere parameter lister?
  • Nevne at dette er et fake eksempel

1.4 first class-functions 1.4 first class-functions Presentation Transcript

  • First class functions
  • First class functionsval even = Function[Int, Boolean] { def apply(i: Int) = i % 2 == 0}val even: (Int => Boolean) = (i: Int) => i % 2 == 0val even = (i: Int) => i % 2 == 0even.apply(42) // trueeven(13) // false
  • First class functionsval numbers = List(1, 2, 3, 4, 5)numbers.filter(even) // List(2, 4)numbers.filter((i: Int) => i > 2) // List(3, 4, 5)numbers.filter(i => i > 2) // List(3, 4, 5)numbers.filter(_ > 2) // List(3, 4, 5)
  • Collectionsnumbers.filter(i => i > 2) // List(3, 4, 5)numbers.find(i => i > 2) // Some(3)numbers.exists(i => i > 2) // truenumbers.forall(i => i > 2) // falsenumbers.map(i => i * 2) // List(2, 4, 6, 8, 10)numbers.foldLeft(0) { (a, b) => a + b } // 15
  • Deferred execution - constructed example helloButton.addActionListener(e => println(“Hello World!”) )
  • Closuresval people = List(Person(“Alf”), Person(“Fredrik”))val name = “Fredrik”val nameFilter = (p: Person) => p.name == namepeople.filter(nameFilter) // Person(“Fredrik”)
  • Closuresval people = List(Person(“Alf”), Person(“Fredrik”))var name = “Fredrik”val nameFilter = (p: Person) => p.name == namepeople.filter(nameFilter) // Person(“Fredrik”)name = “Alf”people.filter(nameFilter) // Person(“Alf”)
  • Tasks (30 min)Open the first-class-functions projectTests in packagescalaexamples.firstclassfunctionsAdd @Test to one and one methodFollow instructions in the codeMake the tests pass