Lesson 5. Closures and partial application

 

After reading lesson 5, you’ll be able to

  • Capture values in a lambda expression
  • Use closures to create new functions
  • Simplify this process with partial application

In this lesson, you’ll learn the final key element of functional programming: closures. Closures are the logical consequence of having lambda functions and first-class functions. By combining these lambda functions and first-class functions to create closures, you can dynamically create functions. This turns out to be an incredibly powerful abstraction, though the one that takes the most getting used to. Haskell makes closures much easier to work with by allowing for partial application. By the end of the lesson, you’ll see how partial application makes otherwise confusing closures much easier to work with.

Consider this

In the preceding lesson, you learned how to pass in programming logic to other functions because of first-class functions. For example, you might have a get-Price function that takes a URL and a website-specific price-extraction function:

getPrice amazonExtractor url

Although this is useful, what happens if you need to extract items from 1,000 URLs, but all using amazonExtractor? Is there a way to capture this argument on the fly so you have to pass in only the url parameter for future calls?

5.1. Closures—creating functions with functions

5.2. Example: Generating URLs for an API

5.3. Putting it all together

Summary