Re: Closures: summarizing suggestions a bit...

Slava Pestov <[email protected]> Thu, 03 Feb 2005 16:38:44 -0500
Newsgroups gmane.comp.java.beanshell.devel
Message-ID <[email protected]>
Hi all,

I suggest a syntax for closures, somewhat inspired by Common Lisp, where 
refer to a function object, either named or anonymous, you write #'foo, 
where foo is either a function name, or an anonymous function block 
("lambda").

While #' is a bit ackward, in BeanShell you can reserve the 
currently-unused @ character to look up inside the function namespace -- 
giving the ability to have function object literals. Using @ in a C like 
language is not that weird, and Objective C uses this character.

So, suppose you had a function map() that took a list and a function, 
and returned a new list. You could do:

sq(x) { return x*x; }

map(list,@sq);

For anonymous closures, just use a syntax like

map(list,@(x) { return x*x; });

So its @(arguments) { body }

(in Common Lisp, its #'(lambda (x y) (+ x y)) -- notice the parallel...).

Now, I missed method literals. What you could do is return an object 
that is internally a pair; a 'this', and a BeanShell method to invoke. 
So the syntax could be like:

map(list,myObj.@foo);

Where myObj.@foo is an object that when called in some way, invokes 
myObj.foo(...).

To call a method, function or closure, i think its ok to call the 'do' 
method on it, like in SmallTalk.

void map(list,closure)
{
     for(i = 0; i < list.size(); i++)
         list.set(i,closure.do(list.get(i)));
}

I hope my proposal is considered. I think overloading an unused 
punctuation character is the best way to implement anonymous closures 
and methods-as-arguments while maintaining brevity, without creating 
ambiguous situations.

Patrick Niemeyer wrote:
> Just to summarize a few of the alternate suggestions:
> 
> // Extended method-like syntax:
> callable( ... );
> callable( arg, ... );
> 
> 
> // Anonymous inner class-like syntax:
> () { ... }
> (arg) { ... }
> 
> 
> // Multiple curly brace syntax:
> {{ ... }}
> { arg { ... } }
> 
> 
> 
> Pat
> 
> 
> 
> -------------------------------------------------------
> This SF.Net email is sponsored by: IntelliVIEW -- Interactive Reporting
> Tool for open source databases. Create drag-&-drop reports. Save time
> by over 75%! Publish reports on the web. Export to DOC, XLS, RTF, etc.
> Download a FREE copy at http://www.intelliview.com/go/osdn_nl
> _______________________________________________
> Beanshell-developers mailing list
> Beanshell-developers-5NWGOfrQmneRv+LV9MX5uipxlwaOVQ5f@public.gmane.org
> https://lists.sourceforge.net/lists/listinfo/beanshell-developers



-------------------------------------------------------
This SF.Net email is sponsored by: IntelliVIEW -- Interactive Reporting
Tool for open source databases. Create drag-&-drop reports. Save time
by over 75%! Publish reports on the web. Export to DOC, XLS, RTF, etc.
Download a FREE copy at http://www.intelliview.com/go/osdn_nl