From: Timothy H. <tim...@ma...> - 2002-05-28 14:49:02
|
The LL1 list (ll1...@ai...) has been discussing the notion of succinctness as a measure of the power of programming languages and Paul Graham put out a request for implementations of (lambda(n) (lambda(i) (set! n (+ n i)))) in various languages. In Java, one could argue that the most natural way to implement this is using Jscheme with the JS.eval and JS.call methods, i.e. the best way to implement a closure in Java is to use a closure.... import jscheme.JS; import jscheme.SchemeProcedure; .... public static void main(String[] args) { SchemeProcedure PGfun = (SchemeProcedure) JS.eval("(lambda(n) (lambda(i) (set! n (+ n i))))"); SchemeProcedure F = (SchemeProcedure) JS.call(PGfun, new Integer (args[0])); System.out.println( ">>" + JS.call("map",F,JS.eval("(1 2 3 4 5 6 7 8 9 10)"))); } One can do something similar in JRuby, and presumably also in Jython. Note however, that the need to cast objects to "SchemeProcedure" is tiresome. Perhaps we should modify JS.call so that it takes an object and dipatches on the type of that object x before applying it to the other arguments a,b,c,.. if x is a SchemeProcedure -- apply x to the other args of JS.call if x is a String --> call JS.eval to get a SchemeProcedure and proceed as usual e.g. JS.call("map", JS.eval("sin"), JS.eval("'(1 2 3 4 5)")) would be equivalent to JS.eval("(map sin '(1 2 3 4 5))"); otherwise throw a JschemeException.... Then we could write the example code above more concisely as: Object PGfun=JS.eval("(lambda(n) (lambda(i) (set! n (+ n i))))"); Object F = JS.call(PGfun, new Integer(args[0])); System.out.println( ">>" + JS.call("map",F,JS.eval("(1 2 3 4 5 6 7 8 9 10)"))); Even more succinctly, we could write this as: Object F = JS.call("(lambda(n) (lambda(i) (set! n (+ n i))))", new Integer(args[0])); System.out.println( ">>" + JS.call("map",F,JS.eval("(1 2 3 4 5 6 7 8 9 10)"))); ---Tim--- |