chapter three

3 Functional Programming

 

This chapter covers fundamental programming concepts: - Functional programming: Key abstractions that improve composition and testability.

3.1 Partially Applied Functions vs. Currying

It’s fairly common for developers to confuse partially applied functions and currying since both concepts involve manipulating functions and arguments in functional programming. Let’s clarify these concepts.

All the examples in this section will be based on the following function that sums three integers:

def add(x: Int, y: Int, z: Int): Int = x + y + z

Partially Applied Function

A partially applied function is a function created by fixing some of the arguments of a function, resulting in a new function that requires fewer arguments.

Imagine that we frequently need to calculate the result of 5 + y + z. Instead of calling add with x = 5 each time, we can create a partially applied function by fixing the first argument:

val addFive = add(5, _: Int, _: Int)
NOTE

The underscores (_) are placeholders for arguments that will be provided later.

This example creates a partially applied function, addFive, that takes only two arguments instead of three. We can call it this way:

val result = addFive(2, 3)

Partially applied functions help simplify complex functions by pre-fixing some arguments, creating more specialized and potentially more reusable functions.

3.1.1 Currying

3.1.2 Conclusion

3.2 Functors, Applicatives, and Monads

3.2.1 Functors

3.2.2 Applicatives

3.2.3 Monads

3.2.4 The Limitation of Applicatives

3.2.5 Monads to the Rescue

3.3 Closing thoughts

3.4 Summary