I have a discrete union WordContainer that is either a Doc of WordDocument or a Cell of WordTableCell. For the purposes of this specific function each type has the same API in terms of functions. I am using a match expression to determine whether the value is a Doc or a Cell and then have under each case the same code with two different variables.
I have spent some time looking this up and reading documentation to figure out how to remove the duplication. First I thought a type class would be great but those are apparently a foreign concept to F#. Then I thought that maybe an interface could be good, but it seemed like I needed full blown classes for those using actual methods which greatly complicated the type hierarchy that I have right now. Trying to leave the type wrapped and working through that did not work, didn't expect it to but I still tried.
The problem here is that
WordTableCellandWordDocumentoffer similar API's, but don't share a base class or interface. This is called "duck typing".Solution 1: Helper functions
One way to handle this is to factor out the differences by creating your own
addParagraphandaddTablehelper functions:You can then call the unified function like this:
This is basically a poor man's typeclass.
Solution 2: Members
Another solution that is slightly more verbose, but perhaps more extensible, is to create a unified interface on the
WordContainertype by definingAddParagraphandAddTablemembers:You can then call them like this: