SYNTACTIC SUGAR

It would certainly be possible to make the Logger API a bit nicer. For a start, you could try to think of a better name for the Bind operation. When designing monads, it’s always advantageous to name the functions so they make sense within the context of what the monad does. Bind is just a generic name that is rarely meaningful.

On the other hand, it is unfortunately not possible to change the semantics of the API in C# — you will always have to chain calls like in the sample, pass in lambdas, and so on — things that not every programmer may find easy to read or write.

When it comes to applying monads to everyday situations, this is where languages like Haskell and even F# have big advantages, because they have special syntax. In Haskell, a chain is built using the >>= operator mentioned before, which results in a sequence that is a little easier to understand. What’s more, there is also special de-sugaring support for a simple block construct: write a sequence of commands within a block encapsulated with do{...}, and the compiler inserts the >>= calls automatically to create the chain. F# offers the same with its workflow syntax. Both languages also have a lot of variants of the described mechanisms for added flexibility and ease of use.

In C#, such de-sugaring syntax exists only in one place, which is LINQ. The compiler understands the LINQ expression syntax and translates it into calls to extension methods (more about the details of this in Chapter 21). The C# ...

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.