1 What is functional programming?

 

This chapter covers

  • Understanding the benefits of functional programming
  • Defining pure functions
  • Referential transparency, purity, and the substitution model

Functional programming (FP) is based on a simple premise with far-reaching implications: we construct our programs using only pure functions ─in other words, functions that have no side effects. But what are side effects? A function has a side effect if it does something other than simply return a result. This includes, for example, the following cases:

  • Modifying a variable
  • Modifying a data structure in place
  • Setting a field on an object
  • Throwing an exception or halting with an error
  • Printing to the console or reading user input
  • Reading from or writing to a file
  • Drawing on the screen

We’ll provide a more precise definition of side effects later in this chapter, but consider what programming would be like without the ability to do these things or with significant restrictions on when and how these actions could occur. It may be difficult to imagine. How would it be possible to write useful programs at all? If we can’t reassign variables, how would we write simple programs like loops? What about working with data that changes or handling errors without throwing exceptions? How could we write programs that must perform input/output (I/O), like drawing to the screen or reading from a file?

1.1 Understanding the benefits of functional programming

1.1.1 A program with side effects

1.1.2 A functional solution: Removing the side effects

1.2 Exactly what is a (pure) function?

1.3 Referential transparency, purity, and the substitution model

1.4 Conclusion

Summary

sitemap