16    Partial Functions

After reading this lesson, you will be able to:

  • Implement partial functions to abstract commonalities between functions
  • Create new functions by composing partial functions
  • Use a try-catch statement to handle exceptions

After learning about pattern matching, in this lesson, you’ll discover partial functions and how they relate to pattern matching. Partial functions are functions that are defined only for some input. You’ll see how they can be useful to abstract commonalities between functions and how you can compose them to create more complex functionalities. Finally, you’ll see how you can use partial functions to catch and handle exceptions. In the capstone, you’ll use partial functions to define the routes of your HTTP server.

16.1       Partial Functions

Suppose you need to compute operations on integers. In particular, you want to calculate the square root of an integer. But this operation is defined only for non-negative numbers. When dealing with a negative integer, you need to either return the negative value or return zero depending on the context of your application. As a first solution you could use pattern matching and define two functions as follows:

16.2       Use case: Exception Handling

16.3       Summary

16.4       Answers to Quick Checks