In this chapter you will learn

  • how to pass functions as arguments
  • how to use the sortBy function
  • how to use map and filter functions
  • how to return functions from functions
  • how to treat functions as values
  • how to use the foldLeft function
  • how to model immutable data using product types

“ The most damaging phrase in the language is: ‘We’ve always done it this way!’ ”

—Grace Hopper

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 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.

score

static int score(String word) {    return word.replaceAll("a", "").length();
}
Our task is to implement a function called `rankedWords` that satisfies the requirements.This is going to be our approach to all requirements in the book. ![](/images/book/grokking-functional-programming/ab0e465f-a27d-4de2-9623-aeaa375566da.png) ## Impure functions and mutable values strike back

Our task is to write a function that, for a given list of words, returns a list of exactly the same words but sorted by their score (highest to lowest). We will try a few approaches to this problem and then decide which one is the best and why. Let’s start with the very first implementation that comes to mind. We already have a function that returns a score for a given word:

static int score(String word)  {    return word.replaceAll("a", "").length();
}

Version #1: Using `Comparator` and `sort` In Java, when we hear _sort_ we usually think _comparator_ . Let’s follow this intuition and prepare a possible solution to the problem: ``` static Comparator scoreComparator = new Comparator() { public int compare(String w1, String w2) { return Integer.compare(score(w2), score(w1)); } }; ``` `scoreComparator` compares two strings and prefers the one that has a higher `score` ↑ This box means that the value defined in the text will be used and referenced later in the chapter. Now, given a list of words, we can get the results by using the `sort` method that takes the `Comparator` we created: ``` static List rankedWords(List words) { words.sort(scoreComparator); return words; } ``` Now, let’s test the `rankedWords` function we’ve just created: ``` List words = Arrays.asList("ada", "haskell", "scala", "java", "rust"); List ranking = rankedWords(words); System.out.println(ranking); console output: [haskell, rust, scala, java, ada] ``` It worked! `haskell` is at the top of the ranking because its score is `6` \* . There is one problem though. **We mutate the existing words list inside the function!** + Note that the `sort` method returns `void` , making it obvious that it mutates the argument that we passed. This solution violates the rules of a pure function and invites all the problems we’ve discussed in previous chapters. We can do better and do it in Java! \* Note that the `score` function counts the letters that are different than ‘ `a` ’. That’s why “ `haskell` " scored 6. + Please forgive us if you experienced impure function flashbacks while reading the code that mutates existing values. ## Using Java Streams to sort the list Fortunately, Java enables us to use the `Comparator` we created in a way that doesn’t violate the pure function rules: let’s use Java Streams! Pure function - It returns only a single value. - It calculates the return value based only on its arguments. - It doesn’t mutate any existing values. Version #2: Ranking the words using Streams We have a function that returns a score for a given word and a `Comparator` that uses this function internally. Nothing needs to be changed there. We can safely use the Stream API and pass the `scoreComparator` . ``` static List rankedWords( List words ) { return words.stream() ① .sorted(scoreComparator) ② .collect(Collectors.toList()); ③ } ``` ① Returns a new `Stream` , which _produces_ elements from the `words` list. ② Returns a new `Stream` , which produces elements from the previous `Stream` but sorts using the provided `Comparator` . ③ Returns a new `List` by copying all elements from the previous `Stream` . This is how the Stream API works. We are _chaining_ the method calls . After calling `stream()` on a collection, we get a `Stream` object back. Most of the methods in the `Stream` class return a new `Stream` ! And the most important thing: **nothing is mutated in this snippet** . Each method call returns a new immutable object, while `collect` returns a brand new `List` ! THIS IS BIG! Some mainstream languages expose APIs that embrace immutability (e.g., Java Streams). Now that we have a lot better code, let’s check if it works as intended. ``` List words = Arrays.asList("ada", "haskell", "scala", "java", "rust"); List ranking = rankedWords(words); ① System.out.println(ranking); console output: [haskell, rust, scala, java, ada] System.out.println(words); console output: [ada, haskell, scala, java, rust] ② ``` ① `ranking` is a totally new list that holds the resulting ranked words list. ② `words` list stayed the same. Big win! Everything looks correct. We have a function that returns only a single value and doesn’t mutate any existing values. However, it still uses an external value to compute its result. It uses `scoreComparator` , which is defined outside of the scope of the function. That means the `rankedWords` signature doesn’t tell the whole story about what’s going on inside. The Stream API helped, but we need more. \* \* Remember when we discussed functions that lie? They lie when their signatures don’t tell the whole story about their body. ## Function signatures should tell the whole story

When we look at the signature of rankedWords , we may be asking ourselves, how does this function know how to sort given words ? To answer this question a reader of our code would need to go into the implementation. However, ideally, we’d like to have an explanation in the parameter list, which is also expressed in the second rule of a pure function:

The function calculates the return value based only on its arguments. Version #3: Passing algorithms as arguments In the next iteration of our solution, we need to be able to reason about what’s going on inside the function just by looking at its signature. To do that, we need to expose the initially hidden dependency on the `scoreComparator` and require the `Comparator` to be passed as a second parameter. ![](/images/book/grokking-functional-programming/b86843ed-caf1-472a-acff-d034c3a76d54.png) Now, the function is completely pure, and we can reason about what it’s doing just by looking at its signature. Note that the additional parameter means that we need to modify the way we call the function. ``` List words = Arrays.asList("ada", "haskell", "scala", "java", "rust"); List ranking = rankedWords(scoreComparator, words); System.out.println(ranking); console output: [haskell, rust, scala, java, ada] ``` `scoreComparator` compares two strings and prefers the one that has a higher `score` The rules of a pure function may seem strict or unnecessary at first. However, applying these rules makes our code more readable, testable, and maintainable. And the more we think about these rules when we are programming, the more natural the whole process becomes. ## Changing requirements So far, we have tried to fulfill the initial requirements and adhere to the rules of a pure function. We have been trying to optimize the function toward better readability and maintainability. This is important because real-world codebases are more often read than written. It’s also important when business requirements change, and we need to change some code. The easier it is to understand the current code, the easier it is to change it. Version #4: Changing the ranking algorithm Let’s see how the `rankedWords` function will do under the new circumstances. Here are the original and additional requirements:

Original requirements

  • 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.

Additional requirements

  • A bonus score of 5 needs to be added to the score if the word contains a 'c'.

  • The old way of scoring (without the bonus) should still be supported in the code.

The scoring algorithm needs some updates. Fortunately, by following the functional approach, we ended up with a bunch of small functions, and that’s why some of them won’t need to change at all! ![](/images/book/grokking-functional-programming/093a6719-7488-43ed-8e26-d32b69e13938.png) ![](/images/book/grokking-functional-programming/a5d0ef71-ae79-4cf0-8a59-73f553556096.png) Since we are slowly moving toward the functional world, we will now stop using `System.out.println` to print results to the console and just use expressions and their values instead. We were able to implement the new requirement by providing a new version of `Comparator` . We reused exactly the same `rankedWords` function. That’s good. We were able to do it because of the new function parameter we introduced previously. This solution works fine, but there seems to be too much duplication, especially between `scoreComparator` and `scoreWithBonusComparator` . Let’s try to make it even better! ## We just pass the code around! Streams help our code become more functional by providing ways of doing operations on collections in an immutable way. \* But it’s not the only functional thing that is going on here! The first parameter of the `rankedWords` function is a `Comparator` , but if we look closer, we can see that its only responsibility is to convey a behavior, just like a function! \* Java Streams are really great. We will use the ideas behind Java Streams to learn some fundamental concepts of FP. Take a closer look at what is really going on in our `rankedWords` function. **By passing a** `Comparator` **instance, we pass the specific behavior—not an instance of some data.** We are passing the code responsible for ordering two words! Functions do it too. ``` List rankedWords(Comparator comparator, List words) { return words .stream() .sorted(comparator) .collect(Collectors.toList()); } ``` As we can see, the `rankedWords` function takes a `Comparator,` which really is just a piece of code responsible for sorting. The cool thing is we can represent this idea in Java and pass a function as `Comparator` . ``` Comparator scoreComparator = (w1, w2) -> Integer.compare(score(w2), score(w1)); ``` We can use this technique to cut a lot of code. Have a look: ![](/images/book/grokking-functional-programming/17317ef8-1797-4472-a619-e09f465cfb9d.png) Thanks to Java’s function syntax, we can provide (and swap, if requirements change!) a sorting algorithm in just one line of code. ## Using Java’s `Function` values Let’s investigate Java’s `Function` type in more depth and try to use this knowledge to make our solution even better. In Java, the `Function` type represents a function that takes one parameter and returns one result. For example, our `scoreFunction` , which takes a `String` and returns an `int` , could be rewritten as an instance of a `Function` . ![](/images/book/grokking-functional-programming/93d2749f-99b4-485c-8536-024e8f6ff46d.png) ``` Function scoreFunction = w -> w.replaceAll("a", "").length(); ① ``` ① `scoreFunction` is a reference to an object in memory that holds a function from `String` to `Integer` . We can now pass this `scoreFunction` thing around like a normal value. We can say that **our function is stored as an immutable value** ! We can treat it in a way similar to any other reference (e.g., `words` ) THIS IS BIG! Functions _stored_ as values are what FP is really about. To call this function, we need to use the `apply` method. ![](/images/book/grokking-functional-programming/05837874-979c-417f-99fc-5b30e807d57b.png) We can also create another reference to the same value and use it. ``` Function f = scoreFunction; f.apply("java"); → 2 ```

Using functions (static methods)

Using Function values *

static int score(String word) {    return word.replaceAll("a", "").length();
}

score("java"); ①
→ 2

static boolean isHighScoringWord(String word) {
  return score(word) > 5;
}

isHighScoringWord("java");
→ false

① We call functions directly by providing the argument. Here, when we call score( "java" ), we get 2 as a result.

Function<String, Integer> scoreFunction =
    w -> w.replaceAll("a", "").length();    ①


scoreFunction.apply("java");                ②
→ 2

Function<String, Boolean> isHighScoringWordFunction =
    w -> scoreFunction.apply(w) > 5;        ③


isHighScoringWordFunction.apply("java");
→ false

① To create a Function value, we need to use the arrow syntax . this definition is equivalent to the one on the legs.

② We can call the functions stored as Function values by calling the apply method.

③ We can reuse Function values in a way similar to how we reuse functions.

\* Note how we use the `->` syntax in Java. It defines a function with no name. On the left, there are arguments, and on the right there is a function body. ## Using the `Function` syntax to deal with code duplication Let’s try to use this newly acquired skill to get rid of the duplication we currently have in our code.

score

scoreWithBonus

static int score(String word) {    return word.replaceAll("a", "").length();
}


static int scoreWithBonus(String word) {
  int base = score(word);
  if (word.contains("c")) return base + 5;
  else return base;
}
static Comparator<String> scoreComparator =    new Comparator<String>() {
    public int compare(String w1, String w2) {
      return Integer.compare(score(w2),
                             score(w1));
    }
  };

rankedWords(scoreComparator, words);
→ [haskell, rust, scala, java, ada]
static Comparator<String> scoreWithBonusComparator =
  new Comparator<String>() {
  public int compare(String w1, String w2) {
    return Integer.compare(scoreWithBonus(w2),
                           scoreWithBonus(w1));
    }
  };

rankedWords(scoreWithBonusComparator, words);
→ [scala, haskell, rust, java, ada]
`scoreComparator` and `scoreWithBonusComparator` are very similar—they differ only in calling different scoring functions. Let’s see how functions shown above look when we create them using Java’s arrow syntax ( `->` ). **These functions are equivalent but stored as values** :
Comparator<String> scoreComparator =      (w1, w2) -> Integer.compare(
                  score(w2),
                  score(w1)
                );
rankedWords(scoreComparator, words);
→ [haskell, rust, scala, java, ada]
Comparator<String> scoreWithBonusComparator = ①
    (w1, w2) -> Integer.compare(
                  scoreWithBonus(w2),
                  scoreWithBonus(w1)
                );
rankedWords(scoreWithBonusComparator, words);
→ [scala, haskell, rust, java, ada]

① To be more precise, Comparator is equivalent to BiFunction , not Function . BiFunction is a type that defines a function with two parameters, while Function is a type for single-parameter functions. We will discuss it further later in the chapter.

Passing function values to a function (i.e., a static method in Java) that expects a `Comparator` looks nice and allows us to reuse big chunks of the code, even when business requirements change. Thanks to this feature, we were able to reuse the `rankedWords` function, which takes both the `words` parameter and the `Comparator` parameter. However, there are still some problems we need to address to make the code even better and more maintainable: - The function we pass to `rankedWords` as a `Comparator` looks too complicated for what it does. We should be able to pass the desired sorting algorithm in a more concise and clean way. - There is still some duplicated code shared between `scoreComparator` and `scoreWithBonusComparator` . The difference between them is only the scoring function used. We should be able to make this fact work to our advantage. ## Passing user-defined functions as arguments We’d like our `rankedWords` function to take something smaller and simpler than the whole `Comparator` , which looks too complicated for what it does. Moreover, when we have two of them, the majority of the code is duplicated. **What we really want is to just specify the scoring behavior.** Maybe we could just pass the scoring behavior as an argument? Fortunately, we have already learned about the technique that is ideal for this job: the `Function` . We can pass the scoring behavior as a parameter! Version #5: Passing the scoring function We don’t have to use `Comparator` as a parameter. The main functionality that we want to pass to the `rankedWords` function is _a way to calculate a score for a given word_ . This is the only thing that has changed in our code because of the business requirements, and therefore, it should be the only customizable thing. **We achieve customization through parameters** . Let’s try to make the `rankedWords` function take another function as a parameter and use it to create the words’ ranking. We are aiming to have a usage like the one below. ``` Function scoreFunction = w -> score(w); rankedWords(scoreFunction, words); → [haskell, rust, scala, java, ada] Function scoreWithBonusFunction = w -> scoreWithBonus(w); rankedWords(scoreWithBonusFunction, words); → [scala, haskell, rust, java, ada] ``` To achieve this kind of API, we need to get a `Function` as a parameter and use it to create a `Comparator` , which is required by the `sort` method of the `Stream` class. Please note that we are able to figure out what this function does just by looking at its signature! **It’s literally ranking the `words` using the `wordScore` scoring algorithm** . THIS IS BIG! Functions that take functions as parameters are ubiquitous in FP code. ``` static List rankedWords(Function wordScore, List words) { Comparator wordComparator = ① (w1, w2) -> Integer.compare( wordScore.apply(w2), wordScore.apply(w1) ); return words ② .stream() .sorted(wordComparator) .collect(Collectors.toList()); } ``` ① We take a Function value as a parameter. It means that we allow the scoring behavior to be customizable.Use Comparator is created internally using the scoring function provided inside the given wordScore value. ② We return a copy of the incoming list by using the immutable-friendly Java Stream API. Now our function can be used in a very concise and readable way. ``` rankedWords(w -> score(w), words); rankedWords(w -> scoreWithBonus(w), words); ``` Note how the caller of the `rankedWords` function is responsible for providing the scoring algorithm. ## Coffee break: Functions as parameters ![](/images/book/grokking-functional-programming/69de9e5b-1913-4309-8b00-c6f3d3dfb3ea.png) It’s your turn to use the power of passing functions as parameters to other functions. We will need to add another requirement to the existing `rankedWords` function. But first, let’s reiterate what we already have.

Requirement: Ranking words

  • 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.

Requirement: Possibility of a bonus

  • A bonus score of 5 needs to be added to the score if the word contains a 'c' .

  • An old way of scoring (without the bonus) should still be supported in the code.

``` static List rankedWords(Function wordScore, List words) { Comparator wordComparator = (w1, w2) -> Integer.compare( wordScore.apply(w2), wordScore.apply(w1) ); return words .stream() .sorted(wordComparator) .collect(Collectors.toList()); } ``` Exercise: Implement the new requirement

New requirement: Possibility of a penalty

  • A penalty score of 7 needs to be subtracted from the score if the word contains an 's' .

  • Old ways of scoring (with and without the bonus) should still be supported in the code.

Note that this is an additional requirement. All the previous requirements still need to be taken into account.

**Your task is to implement a new version of the `rankedWords` function and provide some usage examples in three cases** . - Ranking the words with just a score function (no bonus and no penalty) - Ranking the words with the score + bonus - Ranking the words with the score + bonus - penalty Please think about both a new implementation (body) of `rankedWords` and its API (signature). What does the signature say? Is it self-documenting? How easy it is to figure out what’s going on inside your new version? ## Coffee break explained: Functions as parameters ![](/images/book/grokking-functional-programming/69de9e5b-1913-4309-8b00-c6f3d3dfb3ea.png) Let’s focus on the new requirement first. It looks like the **`rankedWords`** function doesn’t need any change at all! That’s because we have already “outsourced” the scoring algorithm to a `Function` that is passed as an argument. New requirement: Possibility of a penalty - A penalty score of `7` needs to be subtracted from the score if the word contains an `'s'.` - Old ways of scoring (with and without the bonus) should still be supported in the code. So, we need to write a new function that covers all the addends: `base` score, `bonus` , and `penalty` : ``` static int scoreWithBonusAndPenalty(String word) { int base = score(word); int bonus = word.contains("c") ? 5 : 0; ① int penalty = word.contains("s") ? 7 : 0; return base + bonus - penalty; } ``` ① We use Java’s conditional operator, which is an expression that produces a result (in our case, an `int` ). In Java, `if` is a statement, and we can’t use it here. We’ll discuss expressions vs statements in chapter 5. Now, we can just pass this function to `rankedWords` : ``` rankedWords(w -> scoreWithBonusAndPenalty(w), words);” ① → [java, ada, scala, haskell, rust] ``` ① The solution is to pass a different function to our unchanged `rankedWords` function. We can do even better! This part of the chapter is about passing functions, but the whole book is about functions and modeling using functions. That’s why I can’t resist showing you another solution that uses many small independent functions. Each requirement is implemented as a separate function, and all the functions are used when calling `rankedWords` , thanks to the flexibility of the arrow syntax. ```javascript static int bonus(String word) { return word.contains("c") ? 5 : 0; } static int penalty(String word) { return word.contains("s") ? 7 : 0; } rankedWords(w -> score(w) + bonus(w) - penalty(w), words); ① [java, ada, scala, haskell, rust] ``` ① Again, we just pass a different function to our unchanged `rankedWords` function, but this time we use arrow syntax to provide the algorithm inline. It’s very clean and readable because each requirement has its own place in the code. This exercise has many correct solutions, and we can’t showcase every possible one. If your code looks different, but it returns correct results and you haven’t changed anything in the `rankedWords` function, it’s good! ## Problems with reading functional Java Our final solution is very functional in its nature. It respects immutability and pure function rules. And we’ve done it in Java, proving that it’s a very versatile language that’s able to express programs in non-object-oriented paradigms as well. That’s great because we can learn functional concepts without jumping straight into a new language. Unfortunately, there are also some practical problems with using functional programming in Java: we need to write too much code and use mutable `List` s. Too much code to read Opponents of writing fully functionally in Java say that this solution is somewhat bloated and contains a lot of _noise_ . Let’s have a look: ``` static List rankedWords(Function wordScore, List words) { Comparator wordComparator = (w1, w2) -> Integer.compare( wordScore.apply(w2), wordScore.apply(w1) ); return words .stream() .sorted(wordComparator) .collect(Collectors.toList()); } ``` The important bits are in bold. The rest seems to be just a “glue" code.

As we can see, this argument has some merit to it. When it comes to the codebase volume, the most important concern is the reader of the code—not the writer. Code is read far more often than written. Therefore, we should always optimize our code for reading. That means that if we are able to write clean, self-descriptive code using fewer characters, we should usually follow this path.

As we can see, this argument has some merit to it. When it comes to the codebase volume, the most important concern is the reader of the code—not the writer. **Code is read far more often than written. Therefore, we should always optimize our code for reading.** That means that if we are able to write clean, self-descriptive code using fewer characters, we should usually follow this path. We still use mutable `List` s Our solution is a function—a pure one—but it still uses mutable `List` s to get arguments and to return results. We make sure not to mutate the incoming `List` inside the function by using the Java Stream API, but the readers of our code don’t know that by looking at the signature. They see `List` s there, and they can’t safely assume they are not mutated without looking at the implementation. ## Passing functions in Scala It’s about time we move back to writing some Scala code. Let’s fire up the REPL and code together! Over the course of the next few pages, we will first implement the `rankedWords` in Scala and then implement even more requirements using its special function syntax. As a quick reminder, let’s first define and use some small functions in Scala. Then, we’ll try to pass one of them as an argument to a standard library function defined in Scala’s `List` : `sortBy` . For now, please pay attention to how expressive the code is, and don’t worry if you don’t know how `sortBy` works internally—we’ll dive into the details soon. Final reminder: Using code snippets from this book We have been doing a lot of Java in the book so far, and since we are now moving to the FP Scala code, it’s a perfect place for the final reminder that **`>`** at the beginning is a sign that you should execute the Scala REPL in your terminal (by writing `sbt console` ) and then follow the listing. Lines that contain **simplified REPL responses** are marked as →. REPL responses contain the results of the previously entered computation (expression).

>

def inc(x: Int): Int = x + 1        ①  → inc                              ②

inc(2)                              ③
→ 3

def score(word: String): Int =      ④
    word.replaceAll("a", "").length ⑤
→ score                            ⑥

score("java")                       ⑦
→ 2

val words = List("rust", "java")
words: List[String]                 ⑧

words.sortBy(score)                 ⑨
→ List("java", "rust")

① Type code here, and press the Enter key to execute it immediately. Here we define a function in one line!

② The REPL confirms that we defined a function called inc .

③ We call the function inc and pass 2 as x . The REPL prints out the result.

④ We can define even bigger functions in the REPL. When the definition is not complete, and you press Enter, the REPL will wait for more input.

⑤ Here’s a two-line definition of our scoring function.

⑥ The REPL confirms that we defined a function called score . This function will be in scope for the duration of the REPL session.

⑦ We call the function score and pass "java" as an argument. The REPL prints the result: 2 .

⑧ We can create a new value that contains an immutable list with two words. This one is called words , as confirmed by the REPL response.

⑨ We now call the sortBy function defined in Scala’s List class . The sortBy function takes another function as a parameter. It uses it to sort the contents of the list and it returns a new, sorted list as a result, which is printed by the REPL. The words list remains unchanged .

## Deep dive into `sortBy` Let’s have a closer look at the `sortBy` function. We will try to intuitively understand what happens inside this function by looking at our previous REPL session from a different perspective:
1
def score(word: String): Int =    word.replaceAll("a", "").length

We defined a function score that takes a String andreturns an Int . There's nothing new here.

2
val words = List("rust", "java")

We defined a list words that holds multiple String values. Again, this isn't the first time we've done something like this.

3
val sortedWords = words.sortBy(score)

We defined a new list by calling the sortBy method on words.sortBy takes a function that takes a String and returns an Int , calls this function on each element of words , creates a new list and fills it with the elements from words but sorted usingthe corresponding Int value.

4
List("rust", "java").sortBy(score)

Note that we don't have to define words to execute sortBy . sortBy can be executed directly on List("rust", "java") , which is the same immutable list but used only here. The expression on the legs returns exactly the same result.

As you see, we are able to sort the immutable `List("rust", "java")` by calling `sortBy` , which takes one parameter—a function. This function in turn takes a `String` and returns an `Int` . The `sortBy` function uses this function internally to sort the items in the list: ![](/images/book/grokking-functional-programming/77e29482-bd56-457c-a35d-fb890fcbcba2.png) Q Wait, a function that takes a function that takes a `String` ? A Yes, I know it’s a mouthful. This is one of the hardest things to learn in functional programming. It’s also very rewarding! We will practice it a lot until it becomes second nature for you. ![](/images/book/grokking-functional-programming/ac8f65ba-5665-409b-867a-246f52538e08.png) ## Signatures with function parameters in Scala Given our freshly acquired knowledge about the `sortBy` function defined in immutable Scala `List` s, let’s try to rewrite the Java solution in Scala. Here’s the Java code we ended up with: ``` static List rankedWords(Function wordScore, List words) { Comparator wordComparator = (w1, w2) -> Integer.compare( wordScore.apply(w2), wordScore.apply(w1) ); return words .stream() .sorted(wordComparator) .collect(Collectors.toList()); } ``` We concluded that it’s a nice solution, because it doesn’t mutate the incoming `List` and uses a `Function` object to parametrize the ranking algorithm. However, it’s still a lot of code for such a small functionality, and Java’s `List` s are still mutable, so this solution may cause some problems for other teammates. Now, let’s write the `rankedWords` function in Scala, starting with its signature and then moving on to the implementation. The signature As you probably remember, when coding using pure functions, we need to make sure that their signatures are telling the whole truth about what they are doing inside. The signature of a pure function doesn’t lie, and that’s why **the reader of our code can just look at the signature and completely understand what’s going on inside, without even looking at the implementation** . So, what does the signature of the `rankedWords` function look like in Scala compared to Java? THIS IS BIG! Functions that don’t lie are crucial for maintainable codebases. ![](/images/book/grokking-functional-programming/bd35007b-82f0-4b10-8bdc-02ea487485f4.png) In Scala, we use the double-arrow symbol ( `=>` ) to mark parameters that are functions (e.g., `String => Int` above). In Java, we had to write `Function` to achieve a similar result. ## Passing functions as arguments in Scala We have the signature of the `rankedWords` function. Now, it’s time to provide an implementation. Luckily, we already know how to sort lists in Scala. We’ll use the `sortBy` function! First attempt: Using `sortBy` Here’s our score function again: ``` def score(word: String): Int = word.replaceAll("a", "").length ``` Requirement: Ranking words - 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. However, if we use it directly in `sortBy` , we will get an incorrect result. ![](/images/book/grokking-functional-programming/716ba076-481a-477f-bcdc-8780652cfec8.png) `rust` ’s score is higher than `jav` a’s ( `4` to `2` ), but `rust` is listed after `java` in the results. That’s because `sortBy` sorts in ascending order by default. To counter that, we could use an old trick that makes the score negative. ``` def negativeScore(word: String): Int = -score(word) ``` ![](/images/book/grokking-functional-programming/2aeafdb4-c5d8-45b0-bfbd-e98624671c65.png) This works fine, and we can even use it inside our implementation: ``` def rankedWords(wordScore: String => Int, words: List[String]): List[String] = { def negativeScore(word: String): Int = -wordScore(word ① words.sortBy(negativeScore) } ``` ① We can define functions anywhere in our code in Scala. Here we are defining the `negativeScore` function inside the `rankedWords` function. This internal function is available only inside the body of `rankedWords` . This solves our business problem, but it feels hacky. **It’s not the clean code we’d like to have in our projects.** We can do better than that, but before we try a new approach, let’s practice what we’ve learned so far. ## Practicing function passing ![](/images/book/grokking-functional-programming/74bfe78e-a88b-42e7-8c42-852cb4adeadf.png) It’s time to **pass some functions in Scala** . Please use the Scala REPL.

Sort the list of String s by their length in ascending order.

input: List("scala", "rust", "ada")  expected output: List("ada", "rust", "scala")

1

Sort the list of String s provided below by number of the letter 's' inside these String s, in ascending order.

input: List("rust", "ada") expected output: List("ada", "rust")

2

Sort the list of Int s provided below in descending order.

input: List(5, 1, 2, 4, 3) expected output: List(5, 4, 3, 2, 1)

3

Similarly to the second one, sort the list of String s provided below by number of the letter 's' inside these String s but in descending order.

input: List("ada", "rust") output: List("rust", "ada")

4

Answers

>

def len(s: String): Int = s.length  len     ①
List("scala", "rust", "ada").sortBy(len)
→ List("ada", "rust", "scala")

① Note that everything in FP is an expression, and REPL helps us remember that. Each line we input is evaluated, and we get a result. Here, the result is a confirmation that function len was defined. We will only show these “definition” responses in crucial listings, omitting them in the remaining ones.

1

def numberOfS(s: String): Int =
  s.length - s.replaceAll("s", "").length
→ numberOfS
List("rust", "ada").sortBy(numberOfS)
→ List("ada", "rust")

2

def negative(i: Int): Int = -i
→ negative
List(5, 1, 2, 4, 3).sortBy(negative)
→ List(5, 4, 3, 2, 1)

3

def negativeNumberOfS(s: String): Int = -numberOfS(s)
→ negativeNumberOfS
List("ada", "rust").sortBy(negativeNumberOfS)
→ List("rust", "ada")

4

## Embracing declarative programming We managed to implement the `rankedWords` in a few lines of Scala code, but we can do better. Let’s have a look at the code we’ve written so far and make sure we understand why it’s still not good enough. Ranking the words in a hacky way \* ``` def rankedWords(wordScore: String => Int, words: List[String]): List[String] = { def negativeScore(word: String): Int = -wordScore(word) ① words.sortBy(negativeScore) } ``` ① Developer reads: To calculate the score for a word, first make sure we can create a negative score, then use this negative score to sort the words. \* By “hacky," we mean a “working solution developed using a trick." The trick here is the negative scoring system. These are just two lines of code, but a new developer who sees this code for the first time needs to think very carefully. They need to care about the score being negative, which is just an implementation detail of sorting in reverse order. It’s a recipe for reversing the sorting order. And whenever we care about how something is achieved, instead of what needs to be achieved, we are making the code less readable. Ranking the words declaratively The declarative approach focuses on what needs to be done—not how. We can implement `rankedWords` by just stating what needs to be done. In this case we are saying we need the strings sorted by `wordScore` in a natural order (ascending) and reversed. ``` def rankedWords(wordScore: String => Int, words: List[String]): List[String] = { words.sortBy(wordScore).reverse ① } ``` ① Developer reads: The ranked words are sorted by score and reversed. ![](/images/book/grokking-functional-programming/3e5052f8-71c8-49a8-a688-3664e2810613.png) Declarative code is usually more succinct and more comprehensible than imperative code. This approach makes the `rankedWords` function far more concise and readable. ## Passing functions to custom-made functions Our final version of `rankedWords` written in Scala is a pure function that uses immutable `List` s and has a signature that tells the whole truth about its body. So far so good! What we have is this: ``` def rankedWords(wordScore: String => Int, words: List[String]): List[String] = { words.sortBy(wordScore).reverse } ```

But how would we go about using this function? Exactly the same way as we did when we passed functions to the standard library‘s sortBy (i.e., by putting the name of the function as a parameter).

>

def score(word: String): Int = word.replaceAll("a", "").length  rankedWords(score, words)
List("haskell", "rust", "scala", "java", "ada")

Let’s compare this solution to the Java version we previously came up with and try to recap and compare how all the requirements are fulfilled in both versions. Note that we’ll add even more features soon.

Java

Scala

List<String> rankedWords(    Function<String, Integer> wordScore,
  List<String> words
) {
  Comparator<String> wordComparator =
    (w1, w2) -> Integer.compare(
      wordScore.apply(w2),
      wordScore.apply(w1)
    );

    return words.stream()
      .sorted(wordComparator)
      .collect(Collectors.toList());
}
def rankedWords(
  wordScore: String => Int,
  words: List[String]
): List[String] = {
  words.sortBy(wordScore).reverse
}








**Requirement #1** Rank the words by the number of letters different than 'a'.
static int score(String word) {    return word.replaceAll("a", "").length();
}

rankedWords(w -> score(w), words);
→ [haskell, rust, scala, java, ada]
def score(word: String): Int =
  word.replaceAll("a", "").length
  
  
rankedWords(score, words)
→ List("haskell", "rust", "scala", "java", "ada")
**Requirement #2** Additionally, if a word contains a letter 'c', it gets a bonus 5 points.
static int scoreWithBonus(String word) {    int base = score(word);
  if (word.contains("c"))
    return base + 5;
  else
    return base;
}

rankedWords(w -> scoreWithBonus(w), words);
→ [scala, haskell, rust, java, ada]
def scoreWithBonus(word: String): Int = {
  val base = score(word)
  if (word.contains("c")) base + 5 else base
}




rankedWords(scoreWithBonus, words)
→ List("scala", "haskell", "rust", "java", "ada")
## Small functions and their responsibilities Before we move on to implementing more features in our word-ranking code, let’s stop for a bit and talk about _functional software design_ . In this book we want to learn how to use pure functions as the go-to tools when designing and implementing new requirements. Each requirement in this book is implemented as a function—and this doesn’t change even when we get to more advanced requirements later on! Optimizing for readability The main reason programmers are focusing on software design is to make it maintainable. For a piece of code to be maintainable, it needs to be easily understood by programmers on our team, so they can change it quickly and with certainty. That’s why we focus on making the code readable. We apply the same general rules of good design in functional programming as in other programming paradigms. The difference is that we apply them on the function level. Therefore, **we focus on making our functions implement one small business requirement each** . What’s wrong with `scoreWithBonus` then? Here’s our `scoreWithBonus` function. What’s the problem with it? It uses `score` inside but also adds some additional logic on top of it (calculating the bonus). That means it does more than just one thing. ![](/images/book/grokking-functional-programming/bff8bb54-396a-4fda-a8e5-cd9d8adcb375.png) ## Passing functions inline

score

bonus

?

def score(word: String): Int =    word.replaceAll("a", "").length
def bonus(word: String): Int =
  if (word.contains("c")) 5 else 0
So how do we combine results of the `score` function and `bonus` function? We need a technique that is both effective and readable but **doesn’t require a lot of ceremony** . We’ve already used this technique in Java: **anonymous functions** . \* They are usually pretty concise one-liners that don’t need to be named because it’s very obvious what they do. We can define and pass a function to another function in one line of code inside a parameter list. Look at the code comparison below to see how to pass anonymous functions inline in both languages. \* As a counter-example, creating a new named function with several lines of code, like `scoreWithBonus,` is a lot of ceremony. Recap of what we previously did ![](/images/book/grokking-functional-programming/204746d0-eb02-490b-82c2-a417f6f64432.png) Requirement #1 Rank the words by the number of letters different than 'a'.
static int score(String word) {    return word.replaceAll("a", "").length();
}

rankedWords(w -> score(w), words);
→ [haskell, rust, scala, java, ada]
def score(word: String): Int =
  word.replaceAll("a", "").length
  
  
rankedWords(score, words)
→ List("haskell", "rust", "scala", "java", "ada")
Requirement #2 Additionally, if a word contains a letter 'c', it gets a bonus 5 points.                                      Using a separate named function:
static int scoreWithBonus(String word) {    int base = score(word);
  if (word.contains("c"))
    return base + 5;
  else
    return base;
}

rankedWords(w -> scoreWithBonus(w), words);
→ [scala, haskell, rust, java, ada]
def scoreWithBonus(word: String): Int = {
  val base = score(word)
  if (word.contains("c")) base + 5 else base
}




rankedWords(scoreWithBonus, words)
→ List("scala", "haskell", "rust", "java", "ada")
![](/images/book/grokking-functional-programming/ca3e731e-8a16-4847-b3a6-91f06f5b81e5.png) **Requirement #2** Additionally, if a word contains a letter 'c', it gets a bonus 5 points.                                      Using ananonymous function passed inline:
static int bonus(String word) {    return word.contains("c") ? 5 : 0;
}

rankedWords(w -> score(w) + bonus(w), words);
→ [scala, haskell, rust, java, ada]
def bonus(word: String): Int = {
  if (word.contains("c")) 5 else 0
}

rankedWords(w => score(w) + bonus(w), words)
→ List("scala", "haskell", "rust", "java", "ada")
We define a new function that encodes the business requirement of a `bonus` . Then we use it together with the score function inside the anonymous function passed inline. Note that we should pass only very small functions—simple, straightforward one-liners—as anonymous functions. Adding `score` and `bonus` is a perfect example. You can’t read it wrong. And when you pass it as an argument, the code becomes more concise and readable. ## Coffee break: Passing functions in Scala ![](/images/book/grokking-functional-programming/69de9e5b-1913-4309-8b00-c6f3d3dfb3ea.png) It’s your turn to use the power of passing functions as arguments to other functions. We have done this exercise before using Java. Now it’s time to implement the new requirement using Scala and its built-in immutability. We will need to add another requirement to the existing `rankedWords` function. But first, let’s reiterate what we have already done so far. Requirement: Ranking words - 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. ``` def rankedWords(wordScore: String => Int, words: List[String]): List[String] = { words.sortBy(wordScore).reverse } def score(word: String): Int = word.replaceAll("a", "").length ``` This requirement was implemented using two pure functions. Requirement: Possibility of a bonus - A bonus score of `5` needs to be added to the score if the word contains a `'c'` . - An old way of scoring (without the bonus) should still be supported in the code. ``` def bonus(word: String): Int = if (word.contains("c")) 5 else 0 ``` This requirement needed just one additional function. Exercise: Implement the new requirement Similarly to what you already coded in Java, you need to implement the penalty functionality. Before you start, as a hint, first try to show how `rankedWords` is meant to be used for the score and bonus scenario. New requirement: Possibility of a penalty - A penalty score of `7` needs to be subtracted from the score if the word contains an `'s'` . - Old ways of scoring (with and without the bonus) should still be supported in the code. **Your task** . - Show how to rank the words using the `score` function (no bonus and no penalty). - Show how to rank the words using the `score` and `bonus` functions (no penalty). - **Implement a new function that fulfills the new requirement** . - Show how to rank the words with bonus and penalty requirements. ## Coffee break explained: Passing functions in Scala ![](/images/book/grokking-functional-programming/69de9e5b-1913-4309-8b00-c6f3d3dfb3ea.png) Let’s go through all four tasks, one by one. Using `rankedWords` with `score` This is a warm-up task to make sure you remember how we create and pass _named functions_ in Scala.

>

def score(word: String): Int =     word.replaceAll("a", "").length
  
rankedWords(score, words) ①
→ List("haskell", "rust", "scala", "java", "ada")

① If we have a named function that takes a String and returns an Int , we can pass it by stating its name.

Requirement: Ranking words - 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. Using `rankedWords` with `score` and `bonus` In the second warm-up task, we need to add the results of two functions; therefore, we can’t pass them by name. So we need to define a new _anonymous function_ that does the addition and pass it using the function syntax ( `=>` ).

>

def bonus(word: String): Int = if (word.contains("c")) 5 else 0  
rankedWords(w => score(w) + bonus(w), words) ①
→ List("scala", "haskell", "rust", "java", "ada")

① Here we need to define an anonymous function that takes a String (named w ) and returns an Int . We provide its body inline.

Requirement: Possibility of a bonus - A bonus score of `5` needs to be added to the score if the word contains a `'c'` . - An old way of scoring (without the bonus) should still be supported in the code. Implementing the new requirement Now it’s time to do new things. In this book, we teach functional programming and functional software design. It should be pretty obvious by now that when we ask about implementing a new requirement, we expect a new function! Hence:

>

def penalty(word: String): Int = ①    if (word.contains("s")) 7 else 0

① It’s yet another very simple function that implements the requirement directly. Are you bored? Well, maintainable code should be boring. That’s something we all should aim for.

New requirement: Possibility of a penalty - A penalty score of `7` needs to be subtracted from the score if the word contains an `'s'` . - Old ways of scoring (with and without the bonus) should still be supported in the code. Using `rankedWords` with `score` , `bonus` , and `penalty` Because of all those warmups, we now know how to use the new function to fulfill the new requirement. Here’s a very readable anonymous function:

>

rankedWords(w => score(w) + bonus(w) - penalty(w), words) ①  → List("java", "scala", "ada", "haskell", "rust"))

① We define an anonymous function that takes a String (named w ) and returns an Int .

## What else can we achieve just by passing functions? Q OK, I get it! We can sort things by passing a function as an argument. Is this the only thing this new function-passing technique is able to do? A We have sorted many lists in this chapter, so many that someone may think that sorting is the only thing we can do by passing functions. But they would be mistaken! We will use functions as parameters to fulfill many requirements in this chapter and beyond! Furthermore, we won’t be sorting anything in the foreseeable future—I promise. ![](/images/book/grokking-functional-programming/ac8f65ba-5665-409b-867a-246f52538e08.png) The technique of passing functions as arguments is ubiquitous in functional programming. We will learn its other applications by implementing even more features inside our word-ranking system. Let’s see how a hypothetical conversation between a person requesting features and person implementing them could look in the case of the `rankedWords` function we have been working with. ![](/images/book/grokking-functional-programming/12e65afb-4a87-43b5-b729-cd003d08f5bb.png) As you can see, it’s been pretty straightforward until now. We have been just passing functions to the `sortBy` function, but it won’t do this time. Can we implement this new feature in the same concise and readable way? Yes, we can! We’ll implement this and many more features next! ## Applying a function to each element of a list We now have a new requirement to implement. New requirement: Get the scores - We need to know the score of each word in the list of words. - The function responsible for ranking should still work the same (we cannot change any existing function). As a reference: The solution in imperative Java From now on we won’t be solving problems in Java, but in some cases we will still provide for reference imperative solutions in Java, so you can quickly compare how they differ and draw conclusions for yourself. ``` static List wordScores( Function wordScore, List words ) { List result = new ArrayList<>(); ① for(String word : words) { result.add(wordScore.apply(word)); ② } return result; } ``` ① We create a new list that we will be filling with the resulting values. ② We apply a given function for each element, using the `for` loop. The result of the function is added to the resulting list. As you can see, the code above still has the same problems. - It uses mutable collections ( `ArrayList` ). - The code is not very concise. Intuitively, there is far too much code to read for such a small feature. Spoiler alert! The list of problems will almost definitely be the same: mutable collections, impure functions, and/or too much code. As a reference: The solution in Java using Streams Of course, we can also write a somewhat better solution using Java Streams: ``` static List wordScores( Function wordScore, List words ) { return words.stream() .map(wordScore).collect(Collectors.toList()); ① } ``` ① Using `stream()` enables us to work on a copy of the incoming list. We use the Streams `map` to apply a function to each element. If you don’t know `map` , keep reading. Usually, we recommend Streams for these kinds of solutions because they don’t mutate any existing values. However, we won’t be providing reference Java examples using Streams. We will be providing generic, non-Streams versions of reference Java code because it’s how it’s done in other imperative languages and is easier to compare. ## Applying a function to each element of a list using `map` The new requirement can be quickly implemented using the `map` function, which is ubiquitous in functional programming. It’s very similar to the `sortBy` function we have already met because it also takes just one parameter, and this parameter happens to be a function! Let’s look at the implementation of the new requirement using Scala and its built-in immutable `List` that has a `map` function. ``` def wordScores(wordScore: String => Int, words: List[String]): List[Int] = { ① words.map(wordScore) } ``` ① Note how we change the List of `Strings` into a List of `Int` s without any hassle.

As you can see, it’s very similar to the Java Streams version. What map does is it takes each element of the list and applies the function to it, saving the result in a new list that is returned . So, again, it doesn’t mutate anything. The Scala List API supports immutability.

The signature Let’s dive deep into the code and see how it works underneath. As always, we start with the function signature to get a feeling of what’s inside. ![](/images/book/grokking-functional-programming/1f7de3da-8d95-4b7c-83bf-faf54aef4143.png) The body The body of the function consists of just the call to `map` , \* which does all the heavy lifting. Assuming that `words` contain `"rust"` and `"java"` and the function passed as `wordScore` returns a number of letters different than `'a'` , here’s what happens. \* `map` is used instead of the `for` loop we needed in the imperative version. ![](/images/book/grokking-functional-programming/76a2076f-636c-4f2e-a286-95c37007f43e.png) ## Getting to know `map` There are few things related to the `map` function that are always true. Let’s discuss them now. `map` takes only one parameter, and this parameter is a function. If the `List` contains `Strings` , this function needs to take one `String` and return a value of the same or different type. The type of values returned by this function is exactly the type of elements the returned `List` contains. For example: ``` def wordScores(wordScore: String => Int, words: List[String]): List[Int] = { ① words.map(wordScore) } ``` ① Note how we change the `List` of `Strings` into a `List` of `Int` s by providing a function that take `String` and returns an `Int` . `map` is called on `words` , which is a `List[String]` . That means the function that we pass to `map` needs to take an element of type `String` . Fortunately, `wordScore` takes `Strings` ! The type of elements returned by `wordScore` is exactly the type of elements the `List` returned from `map` will contain. `wordScore` returns `Int` s; therefore, `map` returns a `List[Int]` . We will use many diagrams in this book for each generic function we meet. We will not use `Strings` and `Int` s in those diagrams. We will denote such things more generically: `Lists` will contain values of type `A` (i.e., `List[A]` ), functions will take elements of type `A` and return elements of type `B` , and `map` will return `List[B]` . In our case `A` is `String` and `B` is `Int` . `List[A].map(f: A => B): List[B]` Applies the function passed as **`f`** to each element of the original list of elements **`A`** , producing a new list with new elements of type **`B`** . Sizes of the incoming and resulting lists are the same. The ordering of elements is preserved. ![](/images/book/grokking-functional-programming/ab483f09-b704-4f7b-9739-209662205f75.png) `map` preserves the ordering, which means that if an element was before another element in the original list, its mapped version will be before as well. Using `map` in practice Let’s look at our solution once again and try to use it with the real scoring function to make sure we are headed in the right direction. `score` gets a word and returns its score `bonus` gets a word and returns its bonus

>

val words = List("ada", "haskell", "scala", "java", "rust")  wordScores(w => score(w) + bonus(w) - penalty(w), words)
→List(1, -1, 1, 2, -3)
`penalty` gets a word and returns its penalty See? Passing functions is very effective. Now, it’s your turn to do it. ## Practicing `map` ![](/images/book/grokking-functional-programming/74bfe78e-a88b-42e7-8c42-852cb4adeadf.png) It’s time to **pass some functions to the `map` function** . Again, please use the Scala REPL to make sure using `map` becomes second nature for you:

Return lengths of the given Strings .

input: List("scala", "rust", "ada")   output: List(5, 4, 3)

1

Return the number of the letter 's' inside the given Strings .

input: List("rust", "ada")   output: List(1, 0)

2

Negate all the given Int s , and return them as a new List .

input: List(5, 1, 2, 4, 0)   output: List(-5, -1, -2, -4, 0)

3

Double all the given Int s, and return them as a new List .

input: List(5, 1, 2, 4, 0)   output: List(10, 2, 4, 8, 0)

4

Answers

>

def len(s: String): Int = s.length  → len
List("scala", "rust", "ada").map(len)
→ List(5, 4, 3)

1

def numberOfS(s: String): Int = 
  s.length - s.replaceAll("s", "").length
→ numberOfS
List("rust", "ada").map(numberOfS)
→ List(1, 0)

2

def negative(i: Int): Int = -i
→ negative
List(5, 1, 2, 4, 0).map(negative)
→ List(-5, -1, -2, -4, 0)

3

def double(i: Int): Int = 2 * i
→ double
List(5, 1, 2, 4, 0).map(double)
→ List(10, 2, 4, 8, 0)

4

## Learn once, use everywhere When you look at the two functions we have created in this chapter, they have many things in common. ``` def rankedWords(wordScore: String => Int, words: List[String]): List[String] = { words.sortBy(wordScore).reverse } def wordScores(wordScore: String => Int, words: List[String]): List[Int] = { words.map(wordScore) } ``` It’s not a coincidence. The pattern of **defining a function that takes a function as parameter is very useful in many more contexts—not just for operations on collections** . For now, we are using collections as a first step to build an intuition for this pattern. When the intuition is built, you will see an opportunity to customize your functions with functional parameters almost everywhere, even beyond collections. THIS IS BIG! Functions that take functions as parameters are ubiquitous in FP code. What else can we achieve by passing functions? Now, let’s go back to the hypothetical conversation between a person requesting features and a person implementing them casually by passing functions as parameters. ![](/images/book/grokking-functional-programming/5538ad9c-2b34-4aaa-ba53-8c65f01195c6.png) We have been passing functions to `sortBy` and `map` functions, and now we have yet another requirement! Can we implement this new feature in the same concise and readable way, passing a function to another function? ## Returning parts of the list based on a condition We now have a new requirement to implement. New requirement: Return high-scoring words - We need to return a list of words that have a score higher than 1 (i.e., high score). - Functionalities implemented so far should still work the same (we cannot change any existing function). Quick exercise: The signature ![](/images/book/grokking-functional-programming/a83bca49-a3e3-4e39-ba59-389e8fcfa706.png) We try to convey functional programming design principles in this book. That’s why we always start designing new features from the function’s signature. It’s about time you try to figure out the signature yourself, directly from the requirements above. Please stop reading for a while, and try to answer this: **what would the signature of a function called** `highScoringWords` **look like in Scala** . Answer in the discussion. As a reference: The solution in imperative Java Before we implement the functional solution, let’s take a look at how an imperative Java solution would look and what kind of problems it would have. ```javascript static List highScoringWords( Function wordScore, List words ) { List result = new ArrayList<>(); ① for (String word : words) { if (wordScore.apply(word) > 1) ② result.add(word); } return result; } ``` ① We create a new list that we will be filling with the resulting values. ② We apply the function for each element using a `for` loop. The result of the function is added to the resulting list if the condition is satisfied. Again, the code above has the same problems: - It uses mutable collections ( `ArrayList` ). - The code is not very concise. Intuitively, there is far too much code to read for such a small feature. The list of problems contains the same, usual suspects. The signature in Scala In Scala (and other FP languages), we can use a `List` that is immutable. ``` def highScoringWords(wordScore: String => Int, words: List[String]): List[String] ``` ## Returning parts of the list using `filter` You have probably already guessed that the new requirement can be quickly implemented using a function from `List` . You are right! This function is called `filter` . It’s very similar to the `sortBy` and `map` functions we have already met because it also takes just one parameter, and this parameter happens to be a function! Let’s look at the implementation of the new requirement using Scala and its built-in immutable `List` that has a `filter` function: ``` def highScoringWords(wordScore: String => Int, words: List[String]): List[String] = { words.filter(word => wordScore(word) > 1) ① } ``` ① We provide a condition for each element. If the condition is true, the element ends up in the resulting list.

What filter does is take each element of the list and apply the provided condition to it, returning only elements that satisfy this condition . Again, it doesn’t mutate anything. The Scala List API supports immutability, so the returned list is a fresh list of elements that satisfied the condition we provided as a function to the filter function.

The signature ![](/images/book/grokking-functional-programming/0c49e84c-ee3c-4cc5-b4f3-b105db64da81.png) The body The body of the function consists of just the call to `filter` , which takes a function that returns a `Boolean` . Assuming that `words` contain `"rust"` and `"java"` , and the function passed as `wordScore` is our production function with bonuses and penalties, here’s what happens. `filter` is used instead of the for loop we needed in the imperative version. ![](/images/book/grokking-functional-programming/fd185c68-9824-4648-8e57-80295b475c50.png) ## Getting to know `filter` `filter` takes only one parameter, and this parameter is a function. If the `List` contains `Strings` , this function needs to take one `String` . However, unlike `map` , this function must always return a `Boolean` value, which is used to decide whether a particular element should be included in the resulting list or not. The type of values returned by `filter` is exactly the same as the type of elements in the original `List` . For example: ``` def highScoringWords(wordScore: String => Int, words: List[String]): List[String] = { words.filter(word => wordScore(word) > 1) ① } ``` ① `filter` takes one parameter that is a function. This function needs to take a `String` and return a `Boolean` . `filter` is called on `words` , which is a `List[String]` . That means the function that we pass to `filter` needs to take an element of type `String` . `wordScore` takes `Strings` , but it returns `Int` s, so we need to create a new function out of it—a function that takes `Strings` and returns `Booleans` . ``` word => wordScore(word) > 1 ``` We use double-arrow syntax to create an anonymous inline function, which returns `true` if the score of the given word is higher than `1` and `false` otherwise. You can think of the function passed to `filter` as a decision function. It decides what should be included in the result. `List[A].filter(f: A => Boolean): List[A]` Applies the function passed as **`f`** to each element of the original list of elements **`A`** , producing a new list with all the elements of type **`A`** for which **`f`** returned `true` . Sizes of the incoming and resulting lists can be different. The ordering of elements is preserved. ![](/images/book/grokking-functional-programming/15dc3e5f-131c-4106-b16c-4973b33d598e.png) `filter` preserves the ordering, which means that if an element was before another element in the original list, it will be before it in the resulting list, assuming both are included. Using `filter` in practice Now that we got to know `filter` better, let’s try to use our new function.

>

val words = List("ada", "haskell", "scala", "java", "rust")  highScoringWords(w => score(w) + bonus(w) - penalty(w), words)
List("java")

score

def score(word: String): Int =    word.replaceAll("a", "").length

bonus

def bonus(word: String): Int =
  if (word.contains("c")) 5 else 0

penalty

def penalty(word: String): Int =
  if (word.contains("s")) 7 else 0
Only `java` has a total score higher than `1` ( `2` , to be exact). We reused all the scoring functions again. The ability to pass functions saved the day. ## Practicing `filter` ![](/images/book/grokking-functional-programming/74bfe78e-a88b-42e7-8c42-852cb4adeadf.png) It’s time to **pass some functions to the `filter` function** . Again, please use the Scala REPL to make sure you really grok the `filter` function:

Return words that are shorter than five characters.

input: List("scala", "rust", "ada")   output: List("rust", "ada")

1

Return words that have more than two of the letter 's' .

input: List("rust", "ada")   output: List()

2

Return a new List with only odd numbers.

input: List(5, 1, 2, 4, 0)   output: List(5, 1)

3

Return a new List with all numbers larger than 4.

input: List(5, 1, 2, 4, 0)   output: List(5)

4

Answers

>

def len(s: String): Int = s.length  → len
List("scala", "rust", "ada").filter(word => len(word) < 5)
→ List("rust", "ada")

1

def numberOfS(s: String): Int =  
    s.length - s.replaceAll("s", "").length
→ numberOfS
List("rust", "ada").filter(word => numberOfS(word) > 2) ①
→ List()

① Note that we can use the function by name only if it returns a Boolean . If not, we need to create an inline anonymous function.

2

def odd(i: Int): Boolean = i % 2 == 1
→ odd
List(5, 1, 2, 4, 0).filter(odd)            ①
→ List(5, 1)

① Note that we can use the function by name only if it returns a Boolean . If not, we need to create an inline anonymous function.

3

def largerThan4(i: Int): Boolean = i > 4
→ largerThan4
List(5, 1, 2, 4, 0).filter(largerThan4)
→ List(5)

4

## Our journey so far ... Before we move on to the next topic, let’s stop for a moment and think about what we’ve learned and what’s still left to grasp. Generally, in this part of the book we have been learning about our fundamental tools: pure functions (chapter 2), immutable values (chapter 3), and how pure functions can be treated as immutable values (this chapter). These three things are all we need to be able to program in a functional way. However, there are multiple ways functions and values interact with each other, and that’s why we need to look at different problems from different perspectives. ![](/images/book/grokking-functional-programming/95680484-a356-4ad3-b3f0-5a9e6442220f.png) Let’s move on to the second step then. There we will encounter yet another requirement that will test out our approach so heavily, we’ll need to come up with a totally new way of doing things. ## Don’t repeat yourself? Let’s go back to our running example and see what happens when we add even more requirements. For now, we can return high-scoring words, and the **code looks very concise and readable** . This is something we’d like to have all the time, even in the light of new and changing requirements. The next requirement will really test our new approach out. ![](/images/book/grokking-functional-programming/ef350cda-c043-4504-833c-1aff15ae1f2a.png) Let’s assume that we need to return high-scoring words from a given list of words for three different cases:
  • A high-scoring word is a word with a score higher than 1 (current implementation).

  • A high-scoring word is a word with a score higher than 0.

  • A high-scoring word is a word with a score higher than 5.

To implement the three cases above, **we need to repeat a lot of code** :

>

def highScoringWords(wordScore: String => Int,                       words: List[String]): List[String] = {
  words.filter(word => wordScore(word) > 1)
}
The current version of the function has the high score boundary hardcoded as 1.

>

def highScoringWords0(wordScore: String => Int,                        words: List[String]): List[String] = {
  words.filter(word => wordScore(word) > 0)
}

def highScoringWords5(wordScore: String => Int,
                      words: List[String]): List[String] = {
  words.filter(word => wordScore(word) > 5)
}
That’s why we need to create two almost exact copies of this function with different names and high score thresholds of 0 and 5, respectively.

>

val words = List("ada", "haskell", "scala", "java", "rust")  highScoringWords(w => score(w) + bonus(w) - penalty(w), words)
→ List("java")
highScoringWords0(w => score(w) + bonus(w) - penalty(w), words)
→ List("ada","scala","java")
highScoringWords5(w => score(w) + bonus(w) - penalty(w), words)
→ List()
Additionally, we need to pass exactly the same scoring function to each of these almost-exact copies. That is a lot of repetition! A lot of repetition! Let’s see what tools we can use to counter it! ## Is my API easy to use? You probably think that the problem with high score boundaries can be solved by adding a third parameter to the `highScoringWords` function. Well, this is certainly a very sound approach, and it’d definitely solve some of the repetition in the code. However, over the next few pages you’ll see that it’s not enough. There is still going to be some nasty repetition there, and worse still, it’s going to happen in the _client code_ : the code that uses our function by using the API that we provided. **Note that in functional codebases, the API is usually the function signature** . Now you know why we focus so much on signatures!

This book teaches functional programming. The main objective, however, is to teach how functional programming solves real-world software problems. Since codebases are read and analyzed more often than written, we need to focus on how our functions are used. The way we implement them is also important but secondary. Our solution will be used by others, and we should keep that in mind at all times .

Without thinking how our API is going to be used ... ![](/images/book/grokking-functional-programming/8c5937f8-ea69-4153-bdad-05d02bc7f953.png) After thinking how our API is going to be used ... SNEAK PEEK! ![](/images/book/grokking-functional-programming/14b73683-477e-4137-82ca-3fed2de2a213.png) ## Adding a new parameter is not enough When you saw the problem with different high score boundaries, hopefully your response was, “It’s an easy fix: let’s add a new parameter and be done with it!” Unfortunately, this is not enough. Let’s see why. As we can see, the new parameter helped because we don’t have to define a new function for each high score threshold. However, some repetition is still there, and it cannot be fixed with a new parameter. We need something more—a technique that will enable us to specify only some parameters of a function and leave other ones for later. To sum it up: ``` def highScoringWords(wordScore: String => Int, words: List[String]): List[String] = { words.filter(word => wordScore(word) > 1) ① } def highScoringWords(wordScore: String => Int, words: List[String], higherThan: Int): List[String] = { words.filter(word => wordScore(word) > higherThan) ② } ``` ① We need to parametrize the function and transform this value into an Int parameter. ② Now our highScoringWords function takes a scoring function, a list of `Strings` , and an `Int` . It still returns a list of `Strings` that are the high-scoring words. Both the scoring function and the `Int` parameter are used to construct an anonymous function that is passed inline to the `filter` function. ``` highScoringWords(w => score(w) + bonus(w) - penalty(w), words, 1) ① → List("java") highScoringWords(w => score(w) + bonus(w) - penalty(w), words, 0) → List("ada", "scala", "java") highScoringWords(w => score(w) + bonus(w) - penalty(w), words, 5) → List() ``` ① Now we can use this new `highScoringWords` function for all three (and more!) cases, without creating a new function for each case.

PROBLEM!

We got rid of some repetitive code, but there is still a lot of it left! We still pass exactly the same scoring function each time we call highScoringWords.

``` def highScoringWords(wordScore: String => Int, ① words: List[String], ① higherThan: Int): List[String] ② ``` ① We'd like to provide `wordScore` and words in one place ... ② ... and the `higherThan` argument in another place to eliminate all the repetition. ## Functions can return functions To solve our problem without repeating ourselves, we need more than just a new parameter, we need a technique that will delay applying this new parameter. We can achieve this by having a function that will return a function. Let’s modify `highScoringWords` function in this manner. Remember that function signatures say a lot about what they do and how they should be used. Signature We start with the signature. Here, **we define our very first function that returns another function** . ``` def highScoringWords(wordScore: String => Int, ① words: List[String]): Int => List[String] ② ``` ① The function takes two parameters! ② Function returns a function that takes an `Int` and returns a `List[String]` Body How can we return a function from a body? We can use the same syntax we’ve been using to pass functions to `sortBy` , `map` , and `filter` . ``` def highScoringWords(wordScore: String => Int, words: List[String]): Int => List[String] = { higherThan => words.filter(word => wordScore(word) > higherThan) ① } ``` ①     • Our return value is a function that takes `higherThan` as a parameter and returns a List\[String\].     • We use `filter` to create this new filtered list of Strings.     • We use `higherThan` inside the function passed to the `filter` function.

1

This is an inline definition of an anonymous function that takes one parameter named higherThan .

2

This is an inline definition of an anonymous function that takes one parameter named higherThan and returns a List[String] created by filtering a list defined as words .

3

This is an inline definition of an anonymous function that takes one parameter named word .

4

This is an inline definition of an anonymous function that takes one parameter named word and returns a Boolean .

## Using functions that can return functions Returning a function from `highScoringWords` allows us to provide two parameters in one place of the code and the third parameter later in the code. Let’s see how we can do it. ![](/images/book/grokking-functional-programming/e6187422-a21a-404e-a649-d84b7c2deb4c.png) Not much code is needed now—and what’s left is very concise. It may even feel like cheating! To get over this feeling, let’s break down the most critical part and try to really understand what’s going on. ![](/images/book/grokking-functional-programming/bb5c5276-2439-4d78-b9e5-1739a5ee1fea.png) ## Functions are values Q So this all means we can return a function from a function and then store it as a `val` under whatever name we want? Just like we can return and store an `Int` , a `String` , or a `List[String]` ? A Yes! This is exactly what it means! Functions are treated like any other values in functional programming. We can pass them as arguments, return them as return results, and reference them through different names (using the `val` syntax). ![](/images/book/grokking-functional-programming/d77edead-eeff-43a1-8a84-800aa76d20b2.png) THIS IS BIG! Functions are treated exactly the same as other values in FP. Functions passed as arguments are values When you look at the parameter list of `highScoringWords` , it has two parameters. **Both are treated equally; both are just immutable values** . ``` def highScoringWords(wordScore: String => Int, words: List[String] ): Int => List[String] = { ① higherThan => words.filter(word => wordScore(word) > higherThan) } ``` ① A value returned from `highScoringWords` is a function that can be used wherever a function that takes a `Int` and returns a `List[String]` is needed. Functions returned from other functions are values But wait, there is more! We were also able to return a function from a function and save it under a name of our choice and call it! We are just passing values We have been passing functions to `sortBy` , `map` , and `filter` functions. However, in Scala and other functional languages, there is no real difference between functions and other values. Before it becomes second nature for you, please treat functions like objects with behaviors. Just like you treat a Java `Comparator` object that holds a single function inside \* : ``` Comparator scoreComparator = new Comparator() { public int compare(String w1, String w2) { return Integer.compare(score(w2), score(w1)); } }; ``` The same intuition works in FP. Functions are just values; you can use them as arguments, you can create them, and you can return them from other functions. You can just pass them around like `Strings` . \* This is one of the hardest things for beginners in FP to learn. I assume that it may still be hard for you, even after reading this chapter. That’s why I offer you an alternative mental model here, and I will make sure to go back to this topic from time to time. ## Coffee break: Returning functions ![](/images/book/grokking-functional-programming/69de9e5b-1913-4309-8b00-c6f3d3dfb3ea.png) During this coffee break session you will rewrite some of the functions you previously wrote. You should get a sense of using functions as real values. You’ll also be returning functions from functions and using them in familiar built-in functions by passing them as arguments. Make sure to think about each requirement (and code it on your computer) before moving on to the answers. **Your task is to implement each of the four following requirements so that their design is good enough to accommodate required changes.** That’s why each exercise contains both an original requirement and its changed version. Make sure each solution uses a function that returns another function.

Return a new List with all numbers larger than 4 .

input: List(5, 1, 2, 4, 0)   output: List(5)

Change: Now return a new List with all numbers larger than 1.

input: List(5, 1, 2, 4, 0)   output: List(5, 2, 4)

1

Hint: 4 and 1 need to be passed as arguments somewhere.

Return a new List that contains only numbers divisible by 5 .

input: List(5, 1, 2, 4, 15)   output: List(5, 15)

Change: Now return a new List that contains only number divisible by 2 .

input: List(5, 1, 2, 4, 15)   output: List(2, 4)

2

Hint: 5 and 2 need to be passed as arguments.

Maybe to a new function?

Return words that are shorter than four characters.

input: List("scala", "ada")   output: List("ada")

Change: Now return words that are shorter than seven characters.

input: List("scala", "ada")   output: List("scala", "ada")

3

Hint: 4 and 7 need to be passed as arguments to a function that returns a function.

Return words that have more than two of the letter 's' inside.

input: List("rust", "ada")   output: List()

Change: Now return words that have more than zero of the letter 's' inside.

input: List("rust", "ada")   output: List("rust")

4

Hint: You can reuse a function called numberOfS from previous pages, but that’s not enough!

## Coffee break explained: Returning functions ![](/images/book/grokking-functional-programming/69de9e5b-1913-4309-8b00-c6f3d3dfb3ea.png) I hope you’ve had fun with this one! As always, there are multiple ways of solving these exercises. If you used functions that return functions and these functions took `Int` s as parameters, that’s great! If you struggled, don’t worry; the moment will come! The more time you’ve spent figuring this out, the closer to the revelation you are. Let’s solve them together. We will use the Scala REPL again. Please follow along, especially if you haven’t managed to finish the exercise yourself. Return a new `List` with all numbers larger than `4` (or `1` ).

>

def largerThan(n: Int): Int => Boolean = i => i > n  → largerThan
List(5, 1, 2, 4, 0).filter(largerThan(4))
→ List(5)
List(5, 1, 2, 4, 0).filter(largerThan(1))
→ List(5, 2, 4)
1 We defined a function `largerThan` , which takes an `Int` and returns a function that can be used inside `filter` . Return a new `List` that contains only numbers divisible by `5` (or `2` ).

>

def divisibleBy(n: Int): Int => Boolean = i => i % n == 0  → divisibleBy
List(5, 1, 2, 4, 15).filter(divisibleBy(5))
→ List(5, 15)
List(5, 1, 2, 4, 15).filter(divisibleBy(2))
→ List(2, 4)
2 We defined a function `divisibleBy` , which takes an `Int` and returns a function that can be used inside `filter` . We then used this function to filter different numbers. Return words that are shorter than four characters (or `7` ).

>

def shorterThan(n: Int): String => Boolean = s => s.length < n  → shorterThan
List("scala", "ada").filter(shorterThan(4))
→ List("ada")
List("scala", "ada").filter(shorterThan(7))
→ List("scala", "ada")
3 We defined a function `shorterThan` , which takes an `Int` and returns a function that can be used inside `filter` . We then used this function to filter different `String` s. Return words that have more than two of the letter `'s'` inside (or more than `0` ).

>

def numberOfS(s: String): Int =    s.length - s.replaceAll("s", "").length
→ numberOfS
def containsS(moreThan: Int): String => Boolean =
      s => numberOfS(s) > moreThan
→ containsS
List("rust", "ada").filter(containsS(2))
→ List()
List("rust", "ada").filter(containsS(0))
→ List("rust")
4 We defined a function `containsS` , which takes an `Int` and returns a function that can be used inside `filter` . Inside this new function, we reused function `numberOfS,` which we defined previously. We then used `containsS` to filter different `String` s. ## Designing functional APIs We introduced a very important concept: functions are just values and can be returned from other functions. In our example we had a problem with our three-parameter function and transformed it into a two-parameter function that returns a one-parameter function. **The logic inside the function didn’t change** —just the signatures—but it made our job a lot easier! Let’s compare it in the classical before-and-after way. Before ![](/images/book/grokking-functional-programming/82f89c16-3622-45f9-841d-6751815beb65.png) After ![](/images/book/grokking-functional-programming/e6768d0f-dc0c-4214-8a06-0cfc0fddf3e4.png)

Note how all the information our client needs can be derived from signatures! By using this technique, we can make sure that clients know their options, and they can write readable, testable, and maintainable code. It’s the foundation of good software design .

## Iterative design of functional APIs Functional programming gives us very versatile tools to design APIs. \* In this part of the book, we are learning about these tools. However, tools alone won’t make us good programmers. We need to know how to use them in different contexts. That’s what we’ll learn later in the book, but in this chapter I’ve shown you one of the most universal ways of writing software and how it can be practiced using FP: **iterative design based on client feedback** . The design changes based on current assumptions. We are shaping our signatures based on the requirements and feedback from the client of our code. Changes are more than welcome. \* And there are not many of them as well, which is a good thing! We have pure functions, immutable values, and functions as values, which we learn about in this chapter. We don’t really need anything more! We, as programmers, should not be surprised when requirements change or become more specific. This is exactly what happens in the next section of this chapter. Let’s see how can we use the tools at our disposal—especially returning functions from functions—to deal with changing requirements. ![](/images/book/grokking-functional-programming/0a42be0a-56c1-40ed-9942-2f7d31d5b0c8.png) As we can see, our API is not as good as we thought. It’s time to reproduce the problem by trying to use two different lists of words. ```java val words = List("ada", "haskell", "scala", "java", "rust") ① val words2 = List("football", "f1", "hockey", "basketball") ① ``` ① Apart from the list of words we've been using so far, we define a new one to simulate how real players would play our word game ( `words2` ). ``` val wordsWithScoreHigherThan: Int => List[String] = ① highScoringWords(w => score(w) + bonus(w) - penalty(w), words) ① val words2WithScoreHigherThan: Int => List[String] = ① highScoringWords(w => score(w) + bonus(w) - penalty(w), words2) ① ``` ① **Here lies the biggest problem** . We need to define a very similar-looking function for each list of words! ```erlang wordsWithScoreHigherThan(1) ① → List("java")) ① wordsWithScoreHigherThan(0) ① → List("ada", "scala", "java") ① wordsWithScoreHigherThan(5) ① → List() ① words2WithScoreHigherThan(1) ② → List("football", "f1", "hockey") ② words2WithScoreHigherThan(0) ② → List("football", "f1", "hockey", "basketball") ② words2WithScoreHigherThan(5) ② → List("football", "hockey") ② ``` ① We use the first function to get high scores for the first list of words. We need three results because there are three different thresholds; hence, we can't do better than three function calls. ② To add insult to injury, we need to use the second function to get high scores for the second list of words. Taking high score thresholds into account makes ourcode even more bloated with three additional function calls! ## Returning functions from returned functions \* When we look closely at the problem we encountered, we can spot some similarities to the problem we have solved previously by returning a function. Let’s recap what we did. \* If you feel dizzy reading such titles, don’t worry: in the next few pages we will introduce a better way to define these things. Before The three -parameter function ``` def highScoringWords(wordScore: String => Int, ① words: List[String], ① higherThan: Int): List[String] ② ``` ① We' wanted to provide `wordScore` and `words` in one place ... ② ... and the `higherThan` argument in another place to eliminate the repetition related to providing different `higherThans` . After The two -parameter function So we transformed the three-parameter function into a two-parameter function that returns a one-parameter function. ``` def highScoringWords(wordScore: String => Int, words: List[String]): Int => List[String] ``` This way we could provide the `Int` ( `higherThan` argument) independently of `wordScore` and `words` . However, we still need to pass `wordScore` and `words` together, and this is what causes our current problem. We want to keep the same scoring algorithm and use different `words` and `higherThan` values. Fortunately, **this looks exactly like the previous problem, so we can use exactly the same tool to solve it** . \* \* This technique has a name and is ubiquitous in functional programming. We will reveal its name very soon! Before The two -parameter function ``` def highScoringWords(wordScore: String => Int ① words: List[String] ② ): Int => List[String] ``` ① Now we'd like provide `wordScore` in one place ... ② ... and the `words` argument in another place to eliminate the repetition related to providing different `words` . After The one -parameter function

So what we need to do is to transform the two-parameter function that returns a one-parameter function into a one-parameter function that returns a one-parameter function that in turn returns another one-parameter function.

No, there is no mistake in the sentence on the left. We really need to do this.

``` def highScoringWords(wordScore: String => Int): Int => List[String] => List[String] ①② ``` ① This function takes one parameter which is a function that takes a `String` and returns an `Int` . ② This function returns a function that takes an Int and returns a function that takes a `List[String]` and returns a new `List[String]` . ## How to return functions from returned functions \* We now know the signature of our new one-parameter function, and we expect it to solve our design problem: we don’t like to provide the same argument over and over again. That’s why we want to make sure each parameter is applied independently. \* Again, if you don’t like reading such titles, don’t worry: soon we will introduce a better way of discussing returning functions. ``` def highScoringWords(wordScore: String => Int): Int => List[String] => List[String] = { ①② higherThan => words => words.filter(word => wordScore(word) > higherThan) ③ } ``` ① This function takes one parameter which is a function that takes a `String` and returns an `Int` . ② This function returns a function that takes an Int and returns a function, which takes a `List[String]` and returns a new `List[String]` . ③     • Our return value is a function that takes `higherThan` as a parameter and returns a function     • This returned function takes `words` as a parameter and returns a `List[String]` .     • We use `filter` to create this new filtered list of `Strings` , just like before.     • We use `higherThan` and `words` inside the function we are passing to the `filter` function.

1

This is an inline definition of ananonymous function that takes one parameter named higherThan .

2

This is an inline definition of an anonymous function that takes one parameter named higherThan and returns another anonymous function that takes one parameter named words .

3

This is an inline definition of ananonymous function that takes one parameter named higherThan and returns another anonymous function that takes one parameter named words and returns a List[String] createdby filtering alist defined as words .

4

This is an inline definition of an anonymous function that takes one parameter named word .

5

This is an inline definition of ananonymous function that takes one parameter named word and returns a Boolean .

As you can see, we use exactly the same double-arrow syntax to define a function that returns a function that returns a function. Now, it’s about time to test out our new implementation and see it in action. ## Using the flexible API built with returned functions Does transforming a three-parameter function into a function that takes just one parameter and returns a function really help solve our problems? Let’s see how can we use the new version of `highScoringWords` . ![](/images/book/grokking-functional-programming/2fccad5a-da6c-4408-b222-c2916b149a8e.png)

1

When I apply the first argument, the scoring function, I will get a function that still needs two arguments to return a result. I can provide them later. Good thing is that this function will "hold" the scoring algorithm and I won't have to repeat it later on. Here is a function that should fulfill all your requirements about high-scoring words. I used the same technique again.

``` val wordsWithScoreHigherThan: Int => List[String] => List[String] = highScoringWords(w => score(w) + bonus(w) - penalty(w)) ```

2

Now you first need to provide a scoring algorithm and then a high score threshold independently. Now I need to provide a high score threshold to get the next function. I can save it as a val if I know that I will have only one high score threshold. However, we already know that there will be different thresholds and different words lists, so we can apply both remaining arguments at once, without naming the "middle" function:

```java val words = List("ada", "haskell", "scala", "java", "rust") val words2 = List("football", "f1", "hockey", "basketball") ``` ```erlang wordsWithScoreHigherThan(1)(words) ① → List("java") wordsWithScoreHigherThan(0)(words2) ① → List("football", "f1", "hockey", "basketball") wordsWithScoreHigherThan(5)(words2) ① → List("football", "hockey") ``` ① Here we apply two arguments at once to the remaining two functions. There are still two function calls underneath: when we provide a high score threshold (higherThan), we get a function back. We don't save it as val and instead we call it immediately with the list of words of our choice. This is only one of the ways we could use this function, but it fits perfectly to this specific case. Note that if we wanted to have full flexibility, we could still use the same highScoringWords function the way we used the three-parameter one, by providing each argument in a separate parameter list. ``` highScoringWords(w => score(w) + bonus(w) - penalty(w))(1)(words) → List("java") ``` It's up to the user of the function to choose which parameters should be fixed (by saving the function as a named val), and which should not (by applying arguments immediately after getting the function in the same line). ## Using multiple parameter lists in functions We now know that returning functions from other functions can be very beneficial for our codebases. The clients of our functions can write less code and still have lots of flexibility. They can write smaller, independent functions with single responsibilities. They are not forced to repeat themselves. However, there is still a slight problem with the syntax. THIS IS BIG! Returning functions is a foundation of designing flexible APIs. Problem: Inconsistency with parameter naming

The problem is that we are not consistent with our function syntax, even inside one function. This works OK, but it may still cause some confusion for the reader. Let’s look at the highScoringWords function as an example:

``` def highScoringWords( wordScore: String => Int ): Int => List[String] => List[String] = { higherThan => words => words.filter(word => wordScore(word) > higherThan) } ``` There are really three parameter lists in this code snippet: - `wordScore: String => Int` - `higherThan: Int` - `words: List[String]` When I write “parameter list," I mean the part of the signature where we define the parameter names and their types. However, we write them in a totally different way. The first one is written as a normal function parameter list, and the rest is written using the double-arrow syntax we have used for unnamed anonymous functions passed inline. **Fortunately, we can use a more consistent syntax** . Note that the first parameter list includes a parameter, which is a function, while the second and third consist of primitive-type parameters. Solution: Multiple parameter lists In Scala and other functional languages, we can use a syntax that allows us to have multiple parameter lists. In our case, we want to have three. ``` def highScoringWords(wordScore: String => Int): Int => List[String] => List[String] = { higherThan => words => words.filter(word => wordScore(word) > higherThan) } ``` Both `highScoringWords` definitions do the same thing. They take a function as a parameter and return a function that takes another parameter and returns a function. They just use a different syntax. ``` def highScoringWords(wordScore: String => Int)(higherThan: Int)(words: List[String]): List[String] = { words.filter(word => wordScore(word) > higherThan) } ``` ## We have been currying! We were able to use the same technique to solve the last two problems: we transformed a multiple-parameter function into a one-parameter function that returns another one-parameter function. This technique is called **currying** . This is what we’ve been doing to solve the last two problems with `highScoringWords` . Currying is named after logician Haskell Curry—the same person who had a programming language named after him. Currying Transforming multiple-parameter functions into a series of one-parameter functions returned from each other is called _currying_ . Currying enables us to create very versatile APIs. Client code can provide each parameter in different—and the most suitable!—part of the codebase. This helps with avoiding repetition and making the code more readable and maintainable because we don’t have to overwhelm the reader with all different parameters at once.
def f(a: A, b: B, c: C): D

  

Uncurried multiple-parameter function that takes three parameters and returns a value of type D

def f(a: A): B => C => D

using "returning functions" synta .

Curried one-parameter function that takes one parameter and returns another one-parameter function which in turn returns a one-parameter function that returns a value of type D *

def f(a: A)(b: B)(c: C): D

using "multiple parameter lists" synta .

Curried one-parameter function that takes one parameter and returns another one-parameter function which in turn returns a one-parameter function that returns a value of type D *

\* This is exactly the same in terms of usage. The only difference is that in “returning functions" syntax we provide only types of the values, while “multiple parameter lists" include all value names. So `highScoringWords` **became curried** when we transformed it into a one-parameter function that returns another function. It allowed us to provide each of three arguments independently of each other! We still needed to define which parameter went first, second, and so on. This order is very important and should be based on the requirements. In the Haskell language, created by Haskell Curry, all functions are curried. That is, all functions in Haskell take just one argument.

1

2

3

Scoring algorith .

The scoring algorithm is used at the beginning of the game and is selected when game mode is chosen.

High score threshol .

The high score threshold is chosen later in the flow of the program when the dificulty setting is chosen (that’s why it’s after scoring).

List of word .

The list of words changes very dynamically each round of the game when a player provides new lists of words.

``` def highScoringWords(wordScore: String => Int)(higherThan: Int)(words: List[String]): List[String] = { words.filter(word => wordScore(word) > higherThan) } ``` ## Practicing currying Let’s go back to the functions we wrote in the previous exercise. Please transform them into curried versions. This exercise should help you gain some muscle memory. Again, please use the Scala REPL to make sure you really grok it. Your tasks

Return a new List with all numbers larger than 4 (pass 4 as an argument) .

input: List(5, 1, 2, 4, 0)   output: List(5)

1

Return a new List that contains numbers divisible by 5 (pass 5 as an argument) .

input: List(5, 1, 2, 4, 15)   output: List(5, 15)

2

Return words that are shorter than four characters (pass 4 as an argument) .

input: List("scala", "ada")   output: List("ada")

3

Return words that have more than two of the letter 's' inside (pass 2 as an argument).

input: List("rust", "ada")   output: List()

4

Answers

>

def largerThan(n: Int)(i: Int): Boolean = i > n  → largerThan
List(5, 1, 2, 4, 0).filter(largerThan(4))
→ List(5)

1

def divisibleBy(n: Int)(i: Int): Boolean = i % n == 0
→ divisibleBy
List(5, 1, 2, 4, 15).filter(divisibleBy(5))
→ List(5, 15)

2

def shorterThan(n: Int)(s: String): Boolean = s.length < n
→ shorterThan
List("scala", "ada").filter(shorterThan(4))
→ List("ada")
def numberOfS(s: String): Int =
  s.length - s.replaceAll("s", "").length
→ numberOfS

3

def containsS(moreThan: Int)(s: String): Boolean =
  numberOfS(s) > moreThan
→ containsS
List("rust", "ada").filter(containsS(2))
→ List()

4

## Programming by passing function values Now let’s go back to the hypothetical conversation between a person requesting features and a person implementing them casually by passing functions as parameters ( _which are just values like_ `Int` s _and_ `List` s _, right?_ ). ![](/images/book/grokking-functional-programming/2b3b7518-15e8-442e-baf0-44440254fb57.png) We’ve got yet another requirement! This time we need to return a cumulative score of all given words, and as always, we want to do it in a purely functional way: passing immutable values (including functions) into pure functions. This way we avoid lots of problems from the get-go!

Higher-order functions

Before we move on to replace another for loop with a one liner, let me highlight a very important thing: the technique of passing functions as parameters to other functions and returning functions from functions is universal in functional codebases. It’s so universal that it has its own name: a function that takes or returns another function is called a higher-order function . sortBy , map , and filter are just examples from the standard library, but we will meet many more and even write some of our own!

The second very important thing is that we will use map , filter , and other higher-order functions not only on collections but other types as well. We learned them once and will use them everywhere.

## Reducing many values into a single value Let’s have a closer look at our new requirement. New requirement: Return cumulative score - We need to return a cumulative score of words provided as an input list. - Functionalities implemented so far should still work the same (we cannot change any existing function). Quick exercise: The signature ![](/images/book/grokking-functional-programming/a83bca49-a3e3-4e39-ba59-389e8fcfa706.png) In functional programming the signature is a very important piece of information. That’s why we always start designing new features from the function’s signature. It’s a very helpful tool that guides the thinking process and the implementation. That’s why I include the following small exercise (again!). Before we move on, I kindly ask you to try to think about the new requirement and **figure out what the signature of a function implementing it would look like** . Answer in the discussion. As a reference: The solution in imperative Java Before we implement the functional solution and uncover the mystery of the function signature, let’s have a look at how the imperative Java solution would look and what kind of problems it has. ``` static int cumulativeScore( Function wordScore, List words ) { int result = 0; ① for (String word : words) { ② result += wordScore.apply(word); } return result; } ``` ① We create a new mutable integer and initiate it with 0. ② We apply a function for each element using a `for` loop. The result of the function is added to the mutable integer we created at the beginning. The code above has problems we are all familiar with: - It uses mutable collections ( `List` ). - The code is not very concise. Intuitively, there is far too much code to read for such a small feature. The signature in Scala Here’s how Scala version of the signature could look: ``` def cumulativeScore(wordScore: String => Int, ① words: List[String]): Int ``` ① Remember that, though it’s very similar to the Java version, it is using an immutable `List` instead! ## Reducing many values into a single one using `foldLeft` You’ve already seen how quickly we have been able to implement all the requirements so far. We used `List` ’s `sortBy` , `map` , and `filter` : functions that take other functions as parameters, use them internally, and return new, immutable values. This new requirement can also be implemented using the same technique. The function we introduce here is called `foldLeft` . Here’s a possible implementation of the new requirement using Scala’s immutable `List` that has the `foldLeft` function: ``` def cumulativeScore(wordScore: String => Int, words: List[String]): Int = { words.foldLeft(0)((total, word) => total + wordScore(word)) ① } ``` ① We provide a function that is able to add the current element to the ongoing total, which starts at 0.

Yes, foldLeft is a little bit different than the previous ones, but the general rule stays the same. What it does is it takes each element of the list, applies the provided function to it and an ongoing total, then passes it to the next element . Again, it doesn’t mutate anything.

The signature ![](/images/book/grokking-functional-programming/34f2f797-f39c-4701-a80b-fb55b1cf871e.png) Here we assume that we passed a `wordScore` function that includes bonus and penalties. The body The body of the function consists of a lone call to `foldLeft` , which takes an `Int` and a function that takes two parameters and returns an `Int` . ![](/images/book/grokking-functional-programming/399ee049-281c-4672-b90c-2e8d95fef6ff.png) ## Getting to know `foldLeft` `foldLeft` accumulates the value by going through all elements of the list and calling a provided function. The value it accumulates is called an _accumulator_ . Its initial value is passed as a first parameter to `foldLeft` . In our case it was `0` —our accumulator was an `Int` with initial value of `0` : ``` words.foldLeft(0) ``` Assuming that `words` is a `List` of `Strings` , the above snippet returns a function that takes a two-parameter function that takes an `Int` and a `String` and returns an `Int` back: ``` words.foldLeft(0)((total, word) => total + wordScore(word)) ① ``` ① We use the double-arrow notation to create an inline anonymous function. This time, though, we create a two-parameter function—not a single-parameter one. As you can see, the syntax is always the same. We just provide the names of the arguments inside parentheses. Internally, `foldLeft` calls the provided function for each element of the words list (passing it as a `word` ) and **accumulates `total` based on the provided function** . For the first element, the function is called using the initial value of the accumulator (in our case: `0` ). The result of the function called for the last element becomes the result of the `foldLeft` . ![](/images/book/grokking-functional-programming/b6d0d908-baa2-4650-b2c8-4142cbeaa41f.png) `List[A].foldLeft(z: B)(f: (B, A) => B): B` Accumulates a value of type **`B`** by applying the function passed as **`f`** to each element of the original list (which holds values of type **`A`** ) and the current accumulator value, which starts at value **`z`** . Each parameter is on its own parameter list, so we can use currying. Only one value is returned. ![](/images/book/grokking-functional-programming/2ba745ee-2b41-4efe-93cb-0289c05abd51.png) ## `foldLeft` must-knows

foldLeft may cause some issues, so let’s go through some interesting things about this function before moving on to the foldLeft exercise. This should give you some much-needed perspective on what’s going on.

Why is it called “ `left` ”? When you look at the order of the calculations, they happen from left to right. `foldLeft` starts at the leftmost element and combines it with the initial value. Then, it proceeds to the next one. ![](/images/book/grokking-functional-programming/809938f7-c384-40ae-a0a8-9daf24de4dbc.png) Is it only used for calculating the sum of integers? No, it’s not just for calculating sums! `foldLeft` can be used anywhere you need to calculate one metric based on any number of values. Summing is just one of the classical examples, but you could (and will) calculate other things like minimum value, maximum value, a value closest to another value, etc. Moreover, we will also see `foldLeft` being used for non-collection types. We’ll also see that the initial value may be a collection! Something we’ll visit later on is a real mind-boggler: if you pass an empty `List` as an initial value, then the result of `foldLeft` is a different `List` ! It’s so similar to Java Streams `reduce` ! We mentioned earlier in this chapter that all of the functionalities could be implemented using Java Streams. They are better than imperative counterparts, but they still have some problems. If you knew Java Streams, this probably helped you a lot. On the other hand, if you didn’t know Streams, it should be far easier for you now after reading this chapter. ⤵ That’s the power of the functional approach. You can reuse the knowledge in multiple places! ## Practicing `foldLeft` ![](/images/book/grokking-functional-programming/74bfe78e-a88b-42e7-8c42-852cb4adeadf.png) It’s time to write your own functions and pass them to `foldLeft` . Again, please use the Scala REPL to make sure you understand this subject. Your tasks

Return a sum of all integers in the given list.

input: List(5, 1, 2, 4, 100)   output: 112

1

Return the total length of all the words in the given list.

input: List("scala", "rust", "ada")   output: 12

2

Return the number of the letter 's' found in all the words in the given list.

input: List("scala", "haskell", "rust", "ada")   output: 3

3

Return the maximum of all integers in the given list.

input: List(5, 1, 2, 4, 15)   output: 15

4

Answers

>

List(5, 1, 2, 4, 100).foldLeft(0)((sum, i) => sum + i)  → 112

1

def len(s: String): Int = s.length
→ len
List("scala", "rust", "ada")
   .foldLeft(0)((total, s) => total + len(s))
→ 12

2

def numberOfS(s: String): Int =
  s.length - s.replaceAll("s", "").length
→ numberOfS
List("scala", "haskell", "rust", "ada")
  .foldLeft(0)((total, str) => total + numberOfS(str))
→ 3

3

List(5, 1, 2, 4, 15)
  .foldLeft(Int.MinValue)((max, i) => if (i > max) i else max)  ①②
→ 15

① The initial value needs to be a neutral value in the context of the operation. Here we can’t use 0 because the list may contain a single negative value, and then 0 won’t be the right answer.

② We could also use Math.max(max, i) here.

4

## Modeling immutable data So far we’ve been using `map` , `filter` , and `foldLeft` on lists of `String` and `Int` s. This is usually enough for an introduction, but in real production applications we tend to use more complicated data models. Since this book is about practical and maintainable code that you can write and use on production, we need one more thing to be able to say that our functional toolkit is fully assembled. Remember that `map` , `filter` , and `foldLeft` are functions that take functions as parameters. They and functions that return functions are called higher-order functions. Coupling two pieces of information together If `String` represents the whole entity, our higher-order functions work out of the box. But sometimes the entity consists of two or more pieces of information. For example, if we wanted to model a programming language with its name and the year of its first appearance, we’d be out of luck. Functional languages provide a special language construct to define nonprimitive immutable values that can hold multiple values of different types. In FP, **it’s called a product type** , \* and we encode it as a `case class` in Scala. \* In Kotlin, we encode it as a `data class` . We will discuss why it’s called a “product type" in chapter 7. For now, just assume that it’s a type that represents a combination of other types in a fixed order. In our example, we’d like to model a programming language that has a name and a year of its first appearance. That means we want to couple together two pieces of information: a `String` and an `Int` . ``` case class ProgrammingLanguage(name: String, year: Int) ``` And that’s it! We have just defined a new type. How can we use it? Let’s try it out together. Please follow along in your REPL session.

>

case class ProgrammingLanguage(name: String, year: Int)  → defined case class ProgrammingLanguage

val javalang  = ProgrammingLanguage("Java", 1995)
→ javalang: ProgrammingLanguage
val scalalang = ProgrammingLanguage("Scala", 2004)
→ scalalang: ProgrammingLanguage

javalang.name         ①
→ Java
javalang.year
→ 1995
scalalang.name.length ②
→ 5
(scalalang.year + javalang.year) / 2
→ 1999

① We can use the dot syntax to access internal “fields” of values. This line returns a String , “Java.”

② Because name returns a String , we can use it as any normal String (e.g., get its length) .

We create two values of type `ProgrammingLanguage` by stating its name and providing both values it consists of: a `String` and an `Int` . Note that we don’t have to use a `new` keyword like in Java. Finally, because `year` returns an `Int` , we can use this integer as any other (e.g., to calculate an average first year of appearance for both languages, for what it’s worth). ## Using product types with higher-order functions It turns out that product types are a perfect fit for modeling data. They also play nicely with higher-order functions. Product types are immutable

The first great benefit is that product types are immutable. Once you create a value of a product type, it will stay the same until the end of the world (or program execution). That’s why you can access all the fields in the case class , but you can’t assign any other values to them.

>

val javalang = ProgrammingLanguage("Java", 1995)  → javalang: ProgrammingLanguage
javalang.year = 2021
→ error: reassignment to val
javalang.year
→ 1995
Getting the list of names with `map` Product types and their immutability are used in higher-order functions to create more robust code and bigger pure functions. When you have a list of `ProgrammingLanguage` values and you want just a list of names back:

>

val javalang   = ProgrammingLanguage("Java", 1995)  → val scalalang  = ProgrammingLanguage("Scala", 2004)

val languages = List(javalang, scalalang)
→ List(ProgrammingLanguage("Java", 1995),
        ProgrammingLanguage("Scala", 2004))
 
languages.map(lang => lang.name) ①
→ List("Java", "Scala")  

① map gets a function that takes a ProgrammingLanguage and returns a String .

Getting younger languages with `filter` We can also use `filter` in a similar manner. We just provide a function that takes a `ProgrammingLanguage` and returns a `Boolean` that indicates our decision about whether or not to include this `ProgrammingLanguage` in the resulting list. Note that we get a `List` of `ProgrammingLanguages` back from the `filter` call:

>

languages.filter(lang => lang.year > 2000) ①  → List(ProgrammingLanguage("Scala", 2004))

① filter gets a function that takes a ProgrammingLanguage and returns a Boolean . We write this function using the double-arrow syntax and pass it inline.

## More concise syntax for inline functions As we’ve just seen, product types and higher-order functions play very well together. They are the foundation for all functional applications—those used in production and those we will write in this book. They are so prevalent that Scala (and other languages as well) provides a special syntax for defining the inline functions that require a case-class typed value that is passed to `map` , `filter` , and others. Using `map` and `filter` with the underscore syntax Let’s revisit the previous example in which we used `map` and `filter` . Note how repetitive we are when we try to quickly define and pass functions to `map` and `filter` :

>

val javalang   = ProgrammingLanguage("Java", 1995)  val scalalang  = ProgrammingLanguage("Scala", 2004)

val languages = List(javalang, scalalang)
→ List(ProgrammingLanguage("Java", 1995),
       ProgrammingLanguage("Scala", 2004))
 
languages.map(lang => lang.name)              ①
→ List("Java", "Scala")  

languages.filter(lang => lang.year > 2000)    ②
→ List(ProgrammingLanguage("Scala", 2004))

① We want to get the name, but most of the code is just naming the language lang and then using it to access the name field.

② Same here. We want to get the year, but most of the code is just naming the language lang and then using it to access the year field.

What we can do is use **the underscore syntax** :
lang => lang.name        becomes _.name  lang => lang.year > 2000 becomes _.year > 2000

We don’t really need to name the incoming parameter and can just say we are interested in only one of its fields. Here, the underscore is just a value of type ProgrammingLanguage , but it’s not named explicitly.

Note that **the underscore syntax is just another way of defining a function** ! We are still passing functions to `map` and `filter` but in a more concise way.

>

languages.map(_.name)  List("Java", "Scala")  
languages.filter(_.year > 2000)
List(ProgrammingLanguage("Scala", 2004))
Remember that whenever you see a code snippet with >, make sure to follow along in your own REPL session. Have you followed the programming language snippets? ## Summary That’s it! Now you know that functions are really important in functional programming (surprise!). Let’s summarize all the things we learned. CODE: `CH04_*` Explore this chapter’s source code by looking at `ch04_*` files in the book’s repository. Passing functions as parameters We first learned about sorting and how it’s achieved in Java. `sort` takes a `Comparator` , which is an object, but underneath it only contains an algorithm that compares two items. It turned out that this technique is prevalent in Scala and other functional languages, where we pass functions directly using the double-arrow syntax. Functions that take other functions as parameters are called higher-order functions. The `sortBy` function Then, we sorted a given `List` in Scala by calling the `sortBy` function and providing a function as an argument. Nothing was mutated. `sortBy` is a higher-order function. `map` and `filter` functions \* Later in the chapter we used exactly the same technique to transform the `List` s using the `map` and `filter` functions (and providing them a customization function as a parameter, of course!). Their usage is very similar to the Java Streams version, but in Scala and other FP languages, the `List` s are immutable by default, making the code more robust and maintainable. `map` and `filter` are higher-order functions. \* We will be coming back to many of these functions throughout the book, so make sure you grokked them all! Returning functions from functions Then, we learned that some functions can return functions. We can use this technique to _configure_ a function based on incoming parameters. There is also a special syntax to define many parameter lists that makes the code more readable by making sure all the parameters and their types are inside the signature—it’s called currying. Functions that take other functions as parameters and/or return functions are called higher-order functions. `foldLeft` function Having learned all of the above, we were able to introduce and use the `foldLeft` function, which is able to reduce a list of values to a single value. Examples include summing, but other algorithms are also possible. `foldLeft` is a higher-order function, and it’s curried. It has two parameter lists. Modeling immutable data using product type At the end we introduced product types as a way of coupling several pieces of information together. We learned that they play very well with higher-order functions because they are immutable. `case class` is a Scala implementation of the product type.