Skip to content

Instantly share code, notes, and snippets.

@francescoagati
Created August 11, 2016 10:05
Show Gist options
  • Save francescoagati/ff40472e8171a3b3eac31192f2e78678 to your computer and use it in GitHub Desktop.
Save francescoagati/ff40472e8171a3b3eac31192f2e78678 to your computer and use it in GitHub Desktop.
Function threading with macro inspired from clojure
import haxe.macro.Expr;
import haxe.macro.Context;
using haxe.macro.ExprTools;
using haxe.macro.MacroStringTools;
class FunctionThread {
public static macro function thread(exprs:Array<Expr>) {
var exprs = [ for (expr in exprs) macro var _ = $expr ];
exprs.push(macro _);
return macro $b{exprs};
}
}
import FunctionThread.thread;
class Main {
static function sum(a,b) return a+b;
static function main() {
var x = 0;
var res = thread(
sum(x,1),
sum(_,1),
sum(_,2),
sum(3,_)
);
trace(res);
}
}
// Generated by Haxe 3.3.0
(function () { "use strict";
var HxOverrides = function() { };
HxOverrides.iter = function(a) {
return { cur : 0, arr : a, hasNext : function() {
return this.cur < this.arr.length;
}, next : function() {
return this.arr[this.cur++];
}};
};
var Main = function() { };
Main.sum = function(a,b) {
return a + b;
};
Main.main = function() {
console.log(Main.sum(3,Main.sum(Main.sum(Main.sum(0,1),1),2)));
};
Main.main();
})();
@francescoagati
Copy link
Author

without static analyzer is more clear

// Generated by Haxe 3.3.0
(function () { "use strict";
var HxOverrides = function() { };
HxOverrides.iter = function(a) {
    return { cur : 0, arr : a, hasNext : function() {
        return this.cur < this.arr.length;
    }, next : function() {
        return this.arr[this.cur++];
    }};
};
var Main = function() { };
Main.sum = function(a,b,c) {
    if(c == null) {
        c = 0;
    }
    return a + b + c;
};
Main.main = function() {
    var x = 0;
    var _ = Main.sum(x,1);
    var _1 = Main.sum(_,1,5);
    var _2 = Main.sum(_1,2);
    var _3 = Main.sum(3,_2,7);
    var res = _3;
    console.log(res);
};
Main.main();
})();

@francescoagati
Copy link
Author

With inline of sum and static analyzer the code is
console.log(7)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment