Jorge Gamba (1) [Avatar] Offline
Hi, This book is amazing, I found that you choose structs instead of classes to monadic types, but I note that other coders prefer classes using inheritance and others using nested classes and so on.

I am curious about the reasons in favor of structs, maybe performances, simplicity or what?
Enrico Buonanno (93) [Avatar] Offline
Ok, firstly, it's not entirely true: I use struct for things like `Option` and `Either`, but classes for `List` and `Tree` in ch 9 (both are monadic smilie

So really my choice of struct/class has nothing to do with the type being monadic:

- With `Option` we're just adding a boolean to the payload (the inner value), so using a struct gives a benefit in terms of performance (fewer object allocations).

- On the other hand, a List can be very big so should not go on the stack.

There's really another point that your question highlights, namely, that it's common to translate "union types" (e.g.: None l Some T) with inheritance, so if you go down that route then using structs is no longer possible.

The inheritance approach also has other drawbacks, which I discuss in "3.4.3 Implementing Option"; ultimately I used the implementation that allows the cleanest syntax in client code.

(Notice that I do use inheritance for binary trees in Ch 9; partly to show that there are different ways to implement union types in C#)