Higher order functions
Pure function
Laziness
Pattern matching
Partial application
State / Side effects
Composition
- to Debug?- to Test?
- to Reproduce bugs?
def add(x: Int, y: Int) = x + y
> val people = List(Person("a", 20), Person("b", 10))
people: List[Person] = List(Person(a,20), Person(b,10))
> people.map(_.age)
List[Int] = List(20, 10)
> Seq(20, 10) reduce { (accum, current) => accum + current } Int = 30
> Seq(20, 10) reduce(_ + _)
Int = 30
scala> def length(str:String) = str.size
scala> def simpleValidation(i:Int) = i<5
scala> def isValid = length _ andThen simpleValidation _
scala> isValid("1")
res1: Boolean = true
scala> isValid("1234567890")
res2: Boolean = false
length _ andThen simpleValidation _
simpleValidation( length( input ) )
scala> def length(str:String) : Int = str.size
scala> def simpleValidation(i:Int) : Boolean = i<5
scala> def isValid = length _ andThen simpleValidation _
f _ andThen g _
g( f(x) )
f _ compose g _
f( g(x) )
f orElse g
> def underAge(person: Person) = person.age < 18
> people.filter(underAge)
> people.filter( (person:Person) => person.age < 18 )
> people.filter(_.age < 18)
filter(predicate: (A) ⇒ Boolean) : List[A]
find(predicate: (A) ⇒ Boolean): Option[A]
"It is better to have 100 functions operate on one data structure than to have 10 functions operate on 10 data structures."
Alan J. Perlis