Accessing non-final local variables from a lambda expression
Lawrence Kesteloot
lk at teamten.com
Fri Feb 26 15:53:08 PST 2010
Neal,
> Where it's practical, yes. But there is a difference between
> encouraging a functional style and discouraging an imperative style.
> I admire the solution, but it isn't realistic to expect people to come
> up with it without significantly more time invested than is required
> for the simple solution. Most programmers have a job to do and a life
> outside work.
John's solution is pretty standard in Python, where you'd write:
>>> letters = ['a', 'b', 'c', 'd', 'e']
>>> [letter for index, letter in enumerate(letters) if index % 2 == 0]
['a', 'c', 'e']
This solution creates an extra object (the tuple) per iteration.
John's solution requires a parallel API (one that deals with
two-parameter predicates). The performance of the former would be fine
for most people and may become mainstream enough that people wouldn't
have to "come up with it", it'd be an idiom, as it is in Python. The
Java equivalent would be something like:
<T> Iterable<T> everyOther(Iterable<T> input) {
return makeEnumerated(input)
.filter(#(Enumerated<T> it)(it.getIndex()%2==0))
.map(#(Enumerated<T> it)(it.getValue()));
}
Lawrence
More information about the lambda-dev
mailing list