Scala- functional programming

Vassil Dichev

13.03.2019

From OOP to FP

Object-oriented programming makes code understandable by encapsulating moving parts. Functional programming makes code understandable by minimizing moving parts.

-- Michael Feathers

Functions

  • Math: mapping inputs to outputs
  • Programming: decompose and reuse

Functional programming

  • Referential transparency
  • Functions as first-class

Referential transparency

Referential transparency

Referential transparency

Referential transparency

Referential transparency

Referential transparency

Pure functional programming

  • Total: an output for every input.
  • Deterministic: Same output for the same input.
  • Pure: only effect is computing the output.

Life without mutation

  • Recursion
  • Persistent data structures
  • Local mutation

Recursion

image

Tail recursion

  • @tailrec
  • accumulators

Immutability

Classes should be immutable unless there's a very good reason to make them mutable

-- Joshua Bloch, Effective Java

Immutable objects are simple. Immutable objects are also safer. Immutable objects are always threads-safe.

-- Brian Goetz, Java Concurrency in Practice

Persistent data structures

image

Implement a tail-recursive function

  • size: takes a list, returns size
  • concat: takes 2 lists, returns concatenated list
  • reverse: takes list, returns reversed list

Functions

  • Local functions
  • Function literals

Higher-order functions

Combinators are arguably the most reusable constructs we have in programming

-- Dean Wampler

  • filter
  • map
  • foldLeft

filter

image

map

image

Syntax sugar

image

Additional resources