Easier to read lambdas

Magnus Kristiansen magnusrk+es4 at pvv.org
Tue May 29 08:33:57 PDT 2007


On Tue, 29 May 2007 16:18:06 +0200, Igor Bukanov <igor at mir2.org> wrote:

> To mitigate this I suggest to allow to move the definition of the body
> of lambda used inside an expression statement to the end of the
> statement. This would make possible to write:
>
> array.sort(function(a, b)) a - b;
>
> array.sort(function(a, b)) {
>     if (typeof a != "number" || typeof b != "number")
>         throw "Unexpected type of array element";
>     return a - b;
> }
>
> setTimeout(function(), 1000) {
>    if (someCondition)
>        reportTimeout();
> }

When you're putting the function code outside the statement, it becomes a  
hybrid of using a non-anonymous function and using a lambda. The above  
sorter is not very different from this (apart from being anonymous):

array.sort(comp); function comp(a, b) {
     if (typeof a != "number" || typeof b != "number")
         throw "Unexpected type of array element";
     return a - b;
}

> Here is more examples:
>
> Upper-case the array:
>
> var upper = array.map(function(elem)) elem.toUpperCase();
>
> Do complex SQL transaction:
>
> function doSomethingWithNewPeople() {
>    let selectSQL ="SELECT code, name from people where status='new'";
>    let insertSQL = "INSERT INTO young(name,age) values (?,?)";
>    connection.transaction(function(tx)) {
>        connection.prepare(function(selectStatement), selectSQL) {
>            connection.prepare(function(insertStatement), insertSQL) {
>                selectStatement.executeQuery(function(name, age)) {
>                    if (name.match(/.*Joe/) && age % 2)
>                        insertStatement.execute(name, age);
>                }
>            }
>        }
>    }
> }

This example, in my opinion, shows how the hybrid approach becomes less  
legible than either alternative. With regular lambdas, you can use  
whitespace to separate out the structure of subfunctions. With normal  
functions, they're naturally separated. The hybrid cascade above really  
doesn't make sense to me, especially considering cases with multiple  
lambdas in the same function as Jeff Dyer mentioned.

-- 
Magnus Kristiansen
"Don't worry; the Universe IS out to get you."



More information about the Es4-discuss mailing list