From: Larry Clapp
Subject: Closures in Java (and Lisp, sort of)
Date: 
Message-ID: <slrncfop0p.52q.larry@theclapp.ddts.net>
So I came up with some functionality for the (Java) app at work for
which anonymous inner classes seem appropriate.  I've read & seen that
an anonymous inner class can't access local variables from its
defining method unless you declare them final:

    interface AnInterface {
      String readString();
    }

    public class ClosureWithFinals {
      public AnInterface dest(final String dest) {	// dest is final
	return new AnInterface() {
	  public String readString() { 
	    return dest;
	  }
	};
      }

      public static void main(String[] args) {
	ClosureWithFinals p = new ClosureWithFinals();
	AnInterface d = p.dest("Foo!");
	System.out.println( d.readString() );
      }
    }

Bleah.  (This example doesn't really bother me, but the general
principle does.)

I read online that some guy likes to get around this by using an array
of Objects and stuff the variables in question into it:

    public class IckyClosure {
      public AnInterface dest(String dest) {
	final Object[] locals = new Object[1];		// array of objects
	locals[0] = dest;				// dest goes here
	return new AnInterface() {
	  public String readString() { 
	    return (String) locals[0]; 
	  }
	};
      }

      // main() similar to above
    }

I really dislike this approach; it seems quite ugly, and doesn't allow
use of Java's primitive data types.  So I more-or-less stumbled on
this next approach, which seems fairly elegant (by comparison,
anyway):

    public class Closure {
      public AnInterface dest(String dest) {
	class locals {
	  String label;
	}
	final locals locals = new locals();
	locals.label = dest;
	return new AnInterface() {
	  public String readString() { 
	    return locals.label; 
	  }
	};
      }

      // main() similar to above
    }

... and it struck me that I've re-invented the closure.

So I wondered: how closely does this mirror the implementation of
actual Lisp closures (aside from Lisp figuring out what variables to
close over for you), and would an example like this make it easier for
Lisp newbies to understand closures?

-- Larry

From: Pascal Costanza
Subject: Re: Closures in Java (and Lisp, sort of)
Date: 
Message-ID: <cdicrj$f67$1@newsreader2.netcologne.de>
Larry Clapp wrote:

> So I wondered: how closely does this mirror the implementation of
> actual Lisp closures (aside from Lisp figuring out what variables to
> close over for you),

I haven't implemented Lisp compiler, but I would expect that it can be 
simpler because the compiler should be able to arrange for the variables 
to be captured to already be in memory locations that can be easily 
referred to without the need to make additional copies.

> and would an example like this make it easier for
> Lisp newbies to understand closures?

Yes, I think so.

BTW, see also http://www.madbean.com/blog/2003/49/



Pascal

-- 
Tyler: "How's that working out for you?"
Jack: "Great."
Tyler: "Keep it up, then."
From: Pete Kirkham
Subject: Re: Closures in Java (and Lisp, sort of)
Date: 
Message-ID: <40fd6f8c$0$6440$cc9e4d1f@news-text.dial.pipex.com>
Pascal Costanza wrote:
> I haven't implemented Lisp compiler, but I would expect that it can be 
> simpler because the compiler should be able to arrange for the variables 
> to be captured to already be in memory locations that can be easily 
> referred to without the need to make additional copies.
Assuming standard stack allocation of variables, only if the closure 
can't escape the creating function.

Pete
From: Mark McConnell
Subject: Re: Closures in Java (and Lisp, sort of)
Date: 
Message-ID: <d3aed052.0407200738.6d4afb5b@posting.google.com>
Larry Clapp <·····@theclapp.org> wrote in message news:<····················@theclapp.ddts.net>...
> So I came up with some functionality for the (Java) app at work for
> which anonymous inner classes seem appropriate.  I've read & seen that
> an anonymous inner class can't access local variables from its
> defining method unless you declare them final

[snip]

> 
> I read online that some guy likes to get around this by using an array
> of Objects and stuff the variables in question into it:
> 
>     public class IckyClosure {
>       public AnInterface dest(String dest) {
> 	final Object[] locals = new Object[1];		// array of objects
> 	locals[0] = dest;				// dest goes here
> 	return new AnInterface() {
> 	  public String readString() { 
> 	    return (String) locals[0]; 
> 	  }
> 	};
>       }
> 
>       // main() similar to above
>     }
> 
> I really dislike this approach; it seems quite ugly, and doesn't allow
> use of Java's primitive data types.  So I more-or-less stumbled on
> this next approach, which seems fairly elegant (by comparison,
> anyway):
> 
>     public class Closure {
>       public AnInterface dest(String dest) {
> 	class locals {
> 	  String label;
> 	}
> 	final locals locals = new locals();
> 	locals.label = dest;
> 	return new AnInterface() {
> 	  public String readString() { 
> 	    return locals.label; 
> 	  }
> 	};
>       }
> 
>       // main() similar to above
>     }
> 
> ... and it struck me that I've re-invented the closure.
> 
> So I wondered: how closely does this mirror the implementation of
> actual Lisp closures (aside from Lisp figuring out what variables to
> close over for you), and would an example like this make it easier for
> Lisp newbies to understand closures?
> 
> -- Larry

I'm in the same situation: writing Java at work, but with Lisp in
mind.  I tend to use the approach you call IckyClosure, with naming
conventions like
  final String[] destHolder = new String[1];
  destHolder[0] = dest;
From: Larry Clapp
Subject: [OT] Re: Closures in Java (and Lisp, sort of)
Date: 
Message-ID: <slrncfu6e2.52q.larry@theclapp.ddts.net>
In article <····························@posting.google.com>, Mark
McConnell wrote:
> Larry Clapp <·····@theclapp.org> wrote in message
> news:<····················@theclapp.ddts.net>...
>> So I came up with some functionality for the (Java) app at work for
>> which anonymous inner classes seem appropriate.  I've read & seen
>> that an anonymous inner class can't access local variables from its
>> defining method unless you declare them final
> [snip]
>> I read online that some guy likes to get around this by using an
>> array of Objects and stuff the variables in question into it:
>> 
>>     public class IckyClosure {
>>       public AnInterface dest(String dest) {
>> 	final Object[] locals = new Object[1];		// array of objects
>> 	locals[0] = dest;				// dest goes here
>> 	return new AnInterface() {
>> 	  public String readString() { 
>> 	    return (String) locals[0]; 
>> 	  }
>> 	};
>>       }
>> 
>>       // main() similar to above
>>     }
>> 
> I'm in the same situation: writing Java at work, but with Lisp in
> mind.  I tend to use the approach you call IckyClosure, with naming
> conventions like
>   final String[] destHolder = new String[1];
>   destHolder[0] = dest;

Okay, I'm willing to be convinced.  At least your method is better
than the one I was thinking about in IckyClosure, which would put
multiple locals in the same array:

  final Object[] locals = new Objects[] {
    dest, anInt, aString, anotherObject, eTc
  };

Why would you prefer a separate holder for each var, over a single
holder for all vars?  I can see that there'd be at least a slight
performance hit the first time you allocated the "environment", as the
JVM loaded its class file.  Any other reasons?

-- Larry
From: Mark McConnell
Subject: Re: [OT] Re: Closures in Java (and Lisp, sort of)
Date: 
Message-ID: <d3aed052.0407220532.70255538@posting.google.com>
Larry Clapp <·····@theclapp.org> wrote in message news:<····················@theclapp.ddts.net>...
> In article <····························@posting.google.com>, Mark
> McConnell wrote:
> > [snip]
> > I tend to use the approach you call IckyClosure, with naming
> > conventions like
> >   final String[] destHolder = new String[1];
> >   destHolder[0] = dest;
> 
> Okay, I'm willing to be convinced.  At least your method is better
> than the one I was thinking about in IckyClosure, which would put
> multiple locals in the same array:
> 
>   final Object[] locals = new Objects[] {
>     dest, anInt, aString, anotherObject, eTc
>   };
> 
> Why would you prefer a separate holder for each var, over a single
> holder for all vars?  I can see that there'd be at least a slight
> performance hit the first time you allocated the "environment", as the
> JVM loaded its class file.  Any other reasons?
> 
> -- Larry

It's just a personal preference.  From a Lispy point of view, this is
a closure.  But from a Java point of view, it's a trick.  I need to
remember dest, and I need a final Object that can remember it, so why
not name the Object destHolder?  More seriously (but only slightly
so), it improves readability if my colleagues have to modify that code
later.
From: Pete Kirkham
Subject: Re: [OT] Re: Closures in Java (and Lisp, sort of)
Date: 
Message-ID: <40fff90e$0$6440$cc9e4d1f@news-text.dial.pipex.com>
Mark McConnell wrote:
> It's just a personal preference.  From a Lispy point of view, this is
> a closure.  But from a Java point of view, it's a trick.  I need to
> remember dest, and I need a final Object that can remember it, so why
> not name the Object destHolder?  More seriously (but only slightly
> so), it improves readability if my colleagues have to modify that code
> later.

Again, just a matter of preference, but you can make the holders 
/nearly/ invisible.

public class ClosureExample {
   public static class _int {
     public int _;
     public _int (int v) { _ = v; }
     public String toString () {
       return String.valueOf(_);
     }
   }

   public static _int _ (int v) { return new _int(v); }

   ... same for other types

   public static void main (String[] args) {
     final _int x = _(5);
     final _double y = _(0.5);
     final _String z = _("Hello World");

     System.out.println("x = " + x);
     System.out.println("y = " + y);
     System.out.println("z = " + z);

     new Runnable () {
       public void run () {
         x._++;
         y._--;
         z._ = "(" + x + ", " + y + ")";
         // anything much more complicated &
         // you copy into locals, using
         // finally to set the in/out args
       }
     }.run();

     System.out.println("x = " + x);
     System.out.println("y = " + y);
     System.out.println("z = " + z);
   }
}

Which is only slightly worse than (*x)++ in C.

(not that been only slightly less readable than C is any great boast)


Pete
From: Will Hartung
Subject: Re: Closures in Java (and Lisp, sort of)
Date: 
Message-ID: <2m5us0Fj5m5uU1@uni-berlin.de>
"Larry Clapp" <·····@theclapp.org> wrote in message
·························@theclapp.ddts.net...
> So I came up with some functionality for the (Java) app at work for
> which anonymous inner classes seem appropriate.  I've read & seen that
> an anonymous inner class can't access local variables from its
> defining method unless you declare them final:

No, but it can access class variables that are not final.

Java may well have "closures", but as you've discovered, they're not popular
simply because of the flaming hoops you have to jump through in order to
actually use them. So, they're not "handy" and take "work". Lisp has handy
closures, so we drop them all over the place without a second thought. Java
has Flaming Hoop closures so they never see the light of day.

Regards,

Will Hartung
(·····@msoft.com)
From: Rob Warnock
Subject: Re: Closures in Java (and Lisp, sort of)
Date: 
Message-ID: <1bCdnSKDrOTZu2PdRVn-sQ@speakeasy.net>
Will Hartung <·····@msoft.com> wrote:
+---------------
| Java may well have "closures", but as you've discovered, they're not
| popular simply because of the flaming hoops you have to jump through
| in order to actually use them. So, they're not "handy" and take "work".
+---------------

Well, if "not handy" and "takes work" doesn't disqualify them, then
even *C* "has" closures -- just declare something like this:  ;-}

	struct closure {
	    void *function;
	    void *env_data;
	};

Or to say it another way, the common C idiom of passing both a
callback function and an opaque-data cookie (to be passed to
the function when it's called) is in some sense "just a closure",
split over two args.

+---------------
| Lisp has handy closures, so we drop them all over the place without
| a second thought. Java has Flaming Hoop closures so they never see
| the light of day.
+---------------

Even in C "closures" get used *occasionally* -- I used them once
in some firmware for an ATM interface. [Confession: I prototyped
the code in Scheme, and when I hand-compiled it to C, I couldn't
see any easy way to avoid using a closure, so I used one.]


-Rob

-----
Rob Warnock			<····@rpw3.org>
627 26th Avenue			<URL:http://rpw3.org/>
San Mateo, CA 94403		(650)572-2607
From: Kenny Tilton
Subject: Re: Closures in Java (and Lisp, sort of)
Date: 
Message-ID: <aHmLc.55091$4h7.6569905@twister.nyc.rr.com>
Will Hartung wrote:
> "Larry Clapp" <·····@theclapp.org> wrote in message
> ·························@theclapp.ddts.net...
> 
>>So I came up with some functionality for the (Java) app at work for
>>which anonymous inner classes seem appropriate.  I've read & seen that
>>an anonymous inner class can't access local variables from its
>>defining method unless you declare them final:
> 
> 
> No, but it can access class variables that are not final.
> 
> Java may well have "closures", but as you've discovered, they're not popular
> simply because of the flaming hoops you have to jump through in order to
> actually use them.

Why not just use a macro to hide the flaming... hang on... never mind!

:)

kt


-- 
Cells? Cello? Celtik?: http://www.common-lisp.net/project/cells/
Why Lisp? http://alu.cliki.net/RtL%20Highlight%20Film
From: Antonio Menezes Leitao
Subject: Re: Closures in Java (and Lisp, sort of)
Date: 
Message-ID: <874qo1ofo5.fsf@evaluator.pt>
Kenny Tilton <·······@nyc.rr.com> writes:

> Will Hartung wrote:
>> "Larry Clapp" <·····@theclapp.org> wrote in message
>> ·························@theclapp.ddts.net...
>>
>>>So I came up with some functionality for the (Java) app at work for
>>>which anonymous inner classes seem appropriate.  I've read & seen that
>>>an anonymous inner class can't access local variables from its
>>>defining method unless you declare them final:
>> No, but it can access class variables that are not final.
>> Java may well have "closures", but as you've discovered, they're not
>> popular
>> simply because of the flaming hoops you have to jump through in order to
>> actually use them.
>
> Why not just use a macro to hide the flaming... hang on... never mind!
>

Humm, is that a challenge?

Linj implement closures using (Linj) macros.  Here is one example:

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun compose (f/function g/function) 
  #'(lambda (x) 
      (funcall f (funcall g x))))

(defun main (d/double)
  (princ (funcall (compose #'(sqrt double) #'(abs double)) d)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

The translation to Java is:

///////////////////////////////////////////////////////////////////
import linj.Function;

public class Compose extends Object {

    public static Function compose(final Function f, final Function g) {
        return new Function() {
                   public Object funcall(Object x) {
                       return f.funcall(g.funcall(x));
                   }};
    }

    public static void main(String[] outsideArgs) {
        double d = Double.valueOf(outsideArgs[0]).doubleValue();
        System.out.
         print(compose(new Function() {
                           public Object funcall(Object genericArg) {
                               double arg = ((Number)genericArg).doubleValue();
                               return new Double(Math.sqrt(arg));
                           }},
                       new Function() {
                           public Object funcall(Object genericArg) {
                               double arg = ((Number)genericArg).doubleValue();
                               return new Double(Math.abs(arg));
                           }}).
                funcall(new Double(d)));
    }
}
///////////////////////////////////////////////////////////////////

Yes, the translation tends to be big :-)

Here is another example:

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun map-list (l f)
  (declare (abstract-list l) (procedure f))
  (dotimes (i (size l))
    (funcall f (get l i))))

(defun main ()
  (let ((v (new 'Vector)))
    (add v "One")
    (add v "Two")
    (map-list v #'(lambda (e) (format t "Elem: ~A~%" e)))
    (let ((copy (new 'Vector)))
      (map-list v #'(lambda (e) (add-element copy e)))
      (print copy))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

and its translation:

///////////////////////////////////////////////////////////////////
import java.util.AbstractList;
import java.util.Vector;
import linj.Procedure;

public class Closure1 extends Object {

    // methods

    public static void mapList(AbstractList l, Procedure f) {
        int limit = l.size();
        for (int i = 0; i < limit; ++i) {
            f.funcall(l.get(i));
        }
    }

    public static void main(String[] outsideArgs) {
        Vector v = new Vector();
        v.add("One");
        v.add("Two");
        mapList(v,
                new Procedure() {
                    public void funcall(Object e) {
                        System.out.print("Elem: ");
                        System.out.println(e);
                    }});
        final Vector copy = new Vector();
        mapList(v,
                new Procedure() {
                    public void funcall(Object e) {
                        copy.addElement(e);
                    }});
        System.out.print("" + '\n' + copy + " ");
    }
}
///////////////////////////////////////////////////////////////////

It's not exactly the same as Common Lisp closures but it's close
enough for most uses.

Ant�nio Leit�o.