Chapter 17

Monads

WHAT’S IN THIS CHAPTER?

  • What’s in a typeclass
  • What’s in a monad
  • Two sample monads
  • Why LINQ doesn’t do it for monads

Monads are a construct that is very interesting, mentioned frequently when people discuss functional programming, and forms the basis of many mechanisms found in functional languages. Haskell especially uses monads a lot, and it has been said that you need to understand monads to understand Haskell. Whether that’s true or not, Haskell is a language that surfaces the monad as a first class construct, which makes it particularly simple to explain what they are. You will find some Haskell examples in this chapter, and even without knowing Haskell, these should be easy enough to follow.

Monads are interesting because once you understand their nature, you will find that many APIs you use today, even in C#, can be understood and represented as monads. Unfortunately, mainstream imperative languages like C# haven’t made the step to a formal definition of monad mechanisms. Current .NET and C# implementations of monadic patterns are typically quite loose, and the lack of the kind of special syntax provided in Haskell, or even in F#, means that the code that utilizes monadic APIs remains quite verbose.

Before getting started with the real explanations, my editors insist I try for a basic definition of monads. Here’s my best try: A monad is a description of a particular class of types that can be grouped by a certain commonality of their behavior, coupled ...

Get Functional Programming in C#: Classic Programming Techniques for Modern Projects now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.