Encoders and Decoders for Enums/Custom Types
One issue I've encountered a few times now is dealing with record fields that have a set number of possible values. When the value for a field is a basic type, or is either a basic type or something like Null (Or Maybe::Nothing if we're considering Mint), it's fairly straightforward, I just use the type or a Maybe() with the basic type as argument. But sometimes I need a record field's value to match any one item from a set/list/array/call-it-what-you-may. In those cases I tend to use Enums, which doesn't actually make use of the whole Algebraic Data Type thing, but can actually be pretty helpful with validation-related stuff. To list a few examples of how and why I use that are:
- Internationalization: Having language codes/names/whatever on an Enum and the translation itself as records means I'll get an error if I either try to use a language that I don't have a translation for, or if I forget some field in the data for some language.
- Scoping Records: On one case I wrote an eBook reader and it had a
store Settingsto track the user's preferences, persist it and automatically remember it on future sessions, and I decided to allow the use of different fonts/font-sizes/etc on the Ui and the Content, thus anenum FontScopewith the optionsUiandContentseemed perfect for the job, and would allow me to use the samerecordin both. - Many many times I've used Enums for stuff like Movie Genres, variations of data (Movie vs Series, American Comics vs Japanese Mangas, Images vs Videos and so on), and sure in some cases it might make sense to have a Bool, but then if you have 3 values you're screwed, and in other cases it may be ok to use a String but then you need to manually check if the data is valid and test everything and so on without the help of the type-checking, which seems not-ideal to me.
Using Enums for that stuff is all fine and dandy until you try to (de)serialize this data. If the data structure is simple enough it is not too painful to manually convert and check stuff, but as the data structures get more complex, converting it to and from Object(Or even Json) becomes REALLY painful. I was looking into that when I found #146 and it blew my mind, and I think at the very least that should be in the documentation, maybe in a simplified way, along with a similar example for encoding.
And even more than that, maybe there could be an easier way to write custom encoders/decoders. One common problem I've faced is converting Enum values to strings and vice-versa, and usually that ends with two functions, each with a case expression that takes either a string or said Enum and outputs the other, which obviously means I have to write the conversion thing twice, one for each direction, and that's far from ideal.
Having at least some examples of how to deal with those kinds of situations included in the Documentation would be really helpful.