The Author Online Book Forums are Moving

The Author Online Book Forums will soon redirect to Manning's liveBook and liveVideo. All book forum content will migrate to liveBook's discussion forum and all video forum content will migrate to liveVideo. Log in to liveBook or liveVideo with your Manning credentials to join the discussion!

Thank you for your engagement in the AoF over the years! We look forward to offering you a more enhanced forum experience.

Jorge Gamba (1) [Avatar] Offline
#1
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 (104) [Avatar] Offline
#2
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#)