Folding Things With Functional Programming

Folding things can be fun!

Introduction

In this post, we will discuss the concept of fold in functional programming: fold functions are used to reduce a data structure containing multiple values into a single one. Associated to the idea of fold are the concepts of...

  • recursion: via recursion, fold traverses the different elements of the data structure.
  • summarisation: the data structure with all its elements is reduced to a single value
You may also like: 10 Amazing Scala Collection Functions

In the following example, the class Rectangle can be reduced to a single value representing its area. However, it is not 'foldable' in the sense that there is no recursion involved.