[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Another example for syntactically lightweight closures
- From: Eike Decker <eike@...>
- Date: Wed, 6 Feb 2008 11:06:57 +0100
Zitat von Bret Victor <bret@ugcs.caltech.edu>:
> Miles Bader <miles.bader <at> necel.com> writes:
>
> > |a, b|(a + b)
> > => function (a, b) return (a + b) end
> >
> > |a|{ print (a) }
> > => function (a) print (a) end
>
> I thing I like about Lua syntax is that punctuation is kept minimal,
> and words are used (in, do, end) when that's how you would read the
> code out loud.
I agree.
> Here's an expression closure:
>
> local add = (a,b in a + b)
> => local add = function (a,b) return a + b end
looks nice.
> Here's a statement block closure:
>
> local happyprint = x in do print(x .. "!") end
> => local happyprint = function (x) print(x .. "!") end
>
> table.foreach(t, x in do print(x .. "!") end)
> => table.foreach(t, function (x) print(x .. "!") end)
>
> I'm not perfectly happy with either of these, but it's a start, maybe.
That's not too bad. However I think that there shouldn't exist multiple
lightweight syntaxes. The return keyword is rather long and is the reason why
the line often explodes when passing closures, i.e:
local add = (a,b in a + b)
local add = (a,b in return a + b)
=> local add = function (a,b) return a + b end
However, I think there is no clean method to avoid the return keyword.
What if a new keyword was introduced - let's compare
table.foreach(t, x in do print(x .. "!") end)
table.foreach(t, use x in print(x .. "!") end)
=> table.foreach(t, function (x) print(x .. "!") end)
local add = (a,b in a + b)
local add = use a,b in return a + b end
=> local add = function (a,b) return a + b end
Not much shorter, but viewed with the aspect of "reading out loud makes sense",
such a "use" keyword would make more sense in my opinion.
But there is another thing that is bugging me sometimes and I don't know how to
approach it properly currently: upvalues.
There is often quoted this simplified example:
local cnt = 0
function counter ()
cnt = cnt + 1
return cnt
end
This is tricky to pass as argument without using upvalues outside the function
call, so what about another new keyword here:
table.foreach(t, use x with c = 0 in c = c + 1; print(c, x) end)
=> local c = 0; table.foreach(t, function (x) c = c + 1; print(c,x) end)
(more correctly, the call should be inside a do...end block:
=> do local c = 0; table.foreach(t,...) end
)
So my suggestion here is not really much shorter than the current lua syntax -
however if read out loud, it makes more sense. It also keeps the stuff together
more closely. So the benefit is not really less writing but more clear meaning.
I think this should be the focus.
Eike