4 Functions as Values
In this chapter you will learn how to
- pass functions as arguments
- use the sortBy function
- use map & filter functions
- return functions from functions
- treat functions as values
- use the foldLeft function
- model immutable data using product types
The most damaging phrase in the language is: ‘We’ve always done it this way!’
— Grace Hopper
4.1 Implementing requirements as functions
We spent some time working with pure functions and immutable values. They make up the foundation of functional programming. This chapter focuses on showing how well these two concepts work together. We will discover how helpful it is to think about business requirements in terms of functions and how to treat pure functions as values.
Ranking the words
We need to implement a functionality that ranks words in some word-based puzzle game.
Requirements for the word ranking · the score of a given word is calculated by giving one point for each letter that is not an 'a', · for a given list of words, return a sorted list that starts with the highest-scoring word.
|
Warning: Initial requirements may seem trivial, but be warned that we will be changing them and adding new requirements. This will allow us to check how well our code is prepared for such changes. |
As promised, we will try to implement both requirements as functions. The first requirement is pretty straight-forward, but the second one needs some more analysis to get it right. Let’s start with some pseudocode first:
