block lambda revival, now with semantics

Peter Michaux petermichaux at gmail.com
Sat Jun 4 19:55:35 PDT 2011


On Sun, May 22, 2011 at 9:17 PM, Brendan Eich <brendan at mozilla.com> wrote:
> http://wiki.ecmascript.org/doku.php?id=strawman:block_lambda_revival

Suppose we have a host API to open and close files and we write the
following two functions.

    var withFile = function(filename, fn) {
        var file = openFile(filename);
        fn(file);
        file.close();
    };

    var fileContains = function(filename, needle) {
        withFile('path/to/file.txt', {|file|
            return needle.test(file.getContent()));
        });
    };

I believe the file will not be closed in this case.

This problem is not introduced because of lambdas. This problem exists
already if "fn" throws an error.

Would we be able to do the following to ensure the file is closed if
"fn" is either a function that throws or is a lambda that returns?

    var withFile = function(filename, fn) {
        var file = openFile(filename);
        try {
            fn(file);
        }
        finally {
            file.close();
        }
    };

Peter


More information about the es-discuss mailing list