Adages [entries|reading|network|archive]
simont

[ userinfo | dreamwidth userinfo ]
[ archive | journal archive ]

Fri 2013-07-12 09:41
Adages
LinkReply
[identity profile] strawberryfrog.livejournal.comMon 2013-07-15 16:21
If you're going to parse it at compile time, then any language with first-class functions will do something much simpler than this, unless I'm missing something. in C#:

Func<int, int> doubler = x => x * 2;

in Javascript:

var doubler = function(x) { return x * 2 };

I know, there's no "compile time" in JS. But it's equivalent syntax anyway.

If it's deferred until runtime, then the c# syntax is far more complex and unwieldy but probably more flexible: http://blogs.msdn.com/b/csharpfaq/archive/2009/09/14/generating-dynamic-methods-with-expression-trees-in-visual-studio-2010.aspx
Link Reply to this | Parent | Thread
[personal profile] simontMon 2013-07-15 16:36
any language with first-class functions will do something much simpler than this

Indeed, it's simpler and hence less flexible. Both those examples are more or less fixed in form at compile time; you get to plug in some implicit parameters (e.g. capturing variables from the defining scope) but you can't change the number of statements in the function, as I demonstrated in my half-baked polynomial example above. I don't know C# well at all, but I know that in JS you'd only be able to do my polynomial example by building the function source up in a string and doing an eval.

(OK, I suppose you can build one up in JS by composing smaller functions, along the lines of
var poly = function(x) { return 0; }
for (i = ncoeffs; i-- > 0 ;) {
    builder = function(p, coeff) {
        return function(x) { return x*p(x)+coeff; };
    };
    poly = builder(poly, coeffs[i]);
}
but I've no confidence that running it wouldn't still end up with n function call overheads every time a degree-n polynomial was evaluated. Also, I had to try several times to get the recursion to do the right thing in terms of capturing everything by value rather than reference, so even if that does turn out to work efficiently it still fails the puzzle-game test.)
Link Reply to this | Parent | Thread
[identity profile] strawberryfrog.livejournal.comMon 2013-07-15 16:45
I see - you could vary the number of statements with the "generating dynamic methods with expression trees" method above, but it would be a) checked at runtime not compile-time. and b) fugly. Roslyn may address the second issue somewhat, but probably not the first.
Link Reply to this | Parent
navigation
[ go | Previous Entry | Next Entry ]
[ add | to Memories ]