A Practical Example

Functional programming emphasizes immutability, but it’s equally about designing with state transformation and function composition.

In object-oriented programming, we strive for good object composition. In functional programming, we design with function composition. Rather than mutating state, state is transformed as it flows through the sequence of functions.

Let’s construct an example to see what this difference between imperative and functional style looks like in practice. Let’s say we’re given a list of ticker symbols and our goal is to find the highest-priced stock not exceeding $500.

Let’s start with a sample list of ticker symbols.

 val tickers = List("AAPL", "AMD", "CSCO", "GOOG", "HPQ", "INTC",
  "MSFT", ...

Get Functional Programming: A PragPub Anthology now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.