Lazy binding of for comprehensions

4 views
Skip to first unread message

Christopher Oliver

unread,
Oct 25, 2011, 3:56:51 PM10/25/11
to visag...@googlegroups.com
As I mentioned a very long time ago on this list, the current compiler has no strategy for doing this. The well-known strategy, which I would have expected to be followed, is to translate for comprehensions into higher-order function calls (for which lazy binding (mostly) works) (google for "Monad comprehension" if you're interested), e.g

  var xs = [1, 2, 3];
  var squares =  bind for (x in xs) x * x;

translates to

   var squares = bind map(xs, bound function(x:Integer):Integer { x * x });

As the current compiler and language also lacks parametric polymorphism aka "generics", the generic map function has to be defined over Object and type casts inserted around its inputs and outputs, i.e:

bound function map(input:Object[], f:function(o:Object):Object[]):Object[] {
     if (input == []) then []
     else {
           var x = input[0];
           var xs = input1..];
           [f(x), map(xs, f)];
     }
}

var squares = bind (map(xs as Object[], (function(x:Integer):Integer[] { [x * x] } as Object) as function(Object):Object[])) as Integer[];

Furthermore the current compiler has bugs in binding formal parameters in bound functions, the below is a workaround:

bound function map(input0:Object[], f0:function(o:Object):Object[]):Object[] {
     var input = input0;
     var f = f0;
     if (input == []) then []
     else {
           var x = input[0];
           var xs = input[1..];
           [f(x), map(xs, f)];
     }
}

And this requires relatively minor changes to the compiler, fwiw.
Reply all
Reply to author
Forward
0 new messages