2 Functional programming techniques for concurrency

 

This chapter covers

  • Solving complex problems by composing simple solutions
  • Simplifying functional programming with closures
  • Improving program performance with functional techniques
  • Using lazy evaluation

Writing code in functional programming can make you feel like the driver of fast car, speeding along without the need to know how the underlying mechanics work. In chapter 1, you learned that taking an FP approach to writing concurrent applications better answers the challenges in writing those applications than, for example, an object-oriented approach does. Key concepts, such as immutable variables and purity, in any FP language mean that while writing concurrent applications remains far from easy, developers can be confident that they won’t face several of the traditional pitfalls of parallel programming. The design of FP means issues such as race conditions and deadlocks can’t happen.

In this chapter we’ll look in more detail at the main FP principles that help in our quest to write high-quality concurrent applications. You’ll learn what the principles are, how they work in both C# (as far as possible) and in F#, and how they fit into the patterns for parallel programming.

2.1 Using function composition to solve complex problems

2.1.1 Function composition in C#

2.1.2 Function composition in F#

2.2 Closures to simplify functional thinking

2.2.1 Captured variables in closures with lambda expressions

2.2.2 Closures in a multithreading environment

2.3 Memoization-caching technique for program speedup

2.4 Memoize in action for a fast web crawler

2.5 Lazy memoization for better performance

2.5.1 Gotchas for function memoization

2.6 Effective concurrent speculation to amortize the cost of expensive computations

2.6.1 Precomputation with natural functional support

2.6.2 Let the best computation win

2.7 Being lazy is a good thing

2.7.1 Strict languages for understanding concurrent behaviors

2.7.2 Lazy caching technique and thread-safe Singleton pattern

2.7.3 Lazy support in F#

2.7.4 Lazy and Task, a powerful combination

Summary