Monads are an advanced abstraction mechanism, and the abstraction in Haskell is based on the idea of typeclasses (typeclasses, not type classes). Typeclasses are an abstraction that C# and many other object oriented languages don’t have. Look at the following examples to understand what they do.

Say you have your own data type — a discriminated union in Haskell, very similar to an enum in .NET:

data Food = Pasta | Pizza | Chips

You also have a function that can check whether two given values of type Food are considered equal:

isEqualFood :: Food -> Food -> Bool

isEqualFood Pasta Pasta = True

isEqualFood Pizza Pizza = True

isEqualFood Chips Chips = True

isEqualFood _ _ = False

The variations of the function declare the three special cases explicitly in which the two given parameters are the same — in these cases the result is True. In all other cases, denoted by the use of the wildcard operator _, the result is False.

Using the function on a Haskell console at this stage would render these results:

Main> isEqualFood Pizza Chips


Main> isEqualFood Pizza Pizza



Of course, a check for equality of two values is something you want to be able to do with most data types. In other words, there is a group, a class of types, for which comparing for equality makes sense. In Haskell, a typeclass can be used to describe that class of types. Here’s how a typeclass for the purpose of equality comparison could be written:

class MyEq a where

  isEqual ...

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

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.