3 ms·
You're right, that's the Java/C++ way. I was trying to do it the OCaml way in Java. :-) Ultimately, what I wanted was a way to declare the variants in one pl
by PDoyle 10y ago
You're right, that's the Java/C++ way. I was trying to do it the OCaml way in Java. :-)
Ultimately, what I wanted was a way to declare the variants in one place. I didn't want to repeat myself. The only way I could think of declaring them once, and still being able to both produce and consume values of those types, was with a generic visitor interface.
You've done it with a C++ class hierarchy, which has the following properties that the OCaml solution does not:
First, it needs to repeat the components of each variant type three times: once as field declarations, once as constructor arguments, and once as initialization statements in the constructors. The OCaml one (and my Java one) lets you declare the types, fields, and constructors in one line of code.
Second, your code is arranged into classes, which means that adding a new function (say `toString`) requires adding new code in N places, for N types. In OCaml, you'd just write one new function with N variants. (Of course, your code is better if you want to add a new type.)