HNHacker News
TopNewBestAskShowJobs

CKloukinas

2 karma · joined May 31, 2016

submissionscomments
CKloukinas··on OCaml mimicry in Java
Don't know much OCaml (understatement...) but the way I understand it an OCaml type-switch like the expr one is essentially enumerating the different ways one can construct an expr. True is an expr, so is False, etc. - these are constructors of expr not functions as I see it. So I'd code that in Java/C++ as a hierarchy that uses dynamic binding to achieve the case-specific computation for the evaluation (since in OO, it's the compiler that should be writing the switch'es) - in C++ [edit - some pointers don't render; all fields are pointers to expr]:

struct expr { virtual bool eval() const = 0; }

struct True : public expr {bool eval() const {return true;}};

class Not : public expr { expr exp; public: Not( const expr & e ) : exp( &e ) {} bool eval() const {return e->eval();} };

class And : public expr { expr exp1, *exp2; public: And( const expr & e1, const expr & e2 ) : exp1( &e1 ), exp2( &e2 ) {} bool eval() const {return exp1->eval() && e2->eval();} };

And so forth. Different type constructors -> different sub-classes of the abstract type. Functions operating on the type -> methods of the parent class, that each sub-class overrides.

If instead of expr and True/False we had Shape and Triangle/Rectangle that we're more used to looking as forming a hierarchy, it might make it easier to see my point. Isn't this the Java/C++ way for doing so? If not, what am I missing here?