Scala combines OOP and FP. But how to use FP in practice? Practically Functional gives a fine introduction starting with the following "functional trademarks":
- referential transparency
- higher order functions
- closures
- immutability
Which then are described as "functional idioms" using a classification that looks like this:
Recursion -> HOF -> Combinators -> Monads
where each Level raises the level of abstraction.
Recursion
If functional programming does not allow loops then how do you do something repeatedly? The answer is via recursion. To assist the programmer with that Scala offers nested methods.
Higher Order Functions
HOF are functions which take functions as their arguments. Some examples are:
- foldLeft, foldRight ( catamorphism)
- map ( "mapping" over a collection)
- flatMap ( "map" and afterwards "flatten")
There are three kinds of Combinators:
- Sequential ( first a, then b)
- Disjoint (either a or b)
- Literal(exactly foo)
Monads
Properties:- Typ constructor
- Single argument constructor
- flatMap / >>= (bind)
It is really nice to see such eye opening examples which really help you to understand code better and still do the job:
def readPeople(files: List[String]): List[Person] = {
for {
file <-files
props <-readFile(file)
firstName <-props get"name.first"
lastName <- props get "name.last"
ageString <- props get "age"
age <- toInt(ageString)
} yield new Person(firstName, lastName, age)
}
[1] pdf file