COMMUNITY

Writing F# in Haxe


(Yc) #1

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);
}

(Mark) #2

Really cool, thanks for sharing. Welcome :smiley:

Btw this is perfect material for the Haxe code cookbook , a place where we collect snippets of code in one-page tutorials. Check https://code.haxe.org
Contributing is as simple as writing a markdown page at github here
https://github.com/HaxeFoundation/code-cookbook


(Mark) #3

Cool, it’s live :smiley: