I’ve been looking at Haxe for some time, but never really got to trying it out. After getting into the ML family of languages, I fell in love with Algebraic Data types. And so was really glad to see them in Haxe (aka enum).
To get myself familiar with it I’ve started going through Programming Language Concepts (Sestoft). The code in the book is F#, and I’m using Haxe for the code exercises instead.
So far so good!
import Sys;
/* Haxe implementation of F# code on p.2 of
Programming Language Concepts (Sestoft)
*/
class Main {
/* Function that evaluates a given parse tree.
In the book, this parse tree is generated by the F# version of Lex
But I think writing a lexer to generate such a parse tree using Algebraic Data types
would be trivial.
*/
static public function eval(e:Expr) : Int {
switch e {
case CstI(x) : return x;
case Prim("+", e1, e2) : return eval(e1) + eval(e2) ;
case Prim("-", e1, e2) : return eval(e1) - eval(e2) ;
case Prim("*", e1, e2) : return eval(e1) * eval(e2) ;
case Prim(_) : throw "Unknown primitive";
}
}
static public function main() : Void {
Sys.println (eval( CstI(23)));
Sys.println (eval( Prim("+", Prim("*", CstI(7), CstI(9)), CstI(10))));
}
}
/* Algabreic Data Type for Expression. In F# would be:
type expr =
| CstI of int
| Prim of string * exp * exp
*/
enum Expr {
CstI( x:Int );
Prim( op:String, e1:Expr, e2:Expr);
}