The Poor Man's Lambda - Revisited
When I was writing the early spikes for the Quaere project, I wrote a blog post entitled "The Poor Man's Lambda", back then I used anonymous classes for the "lambda" expressions.
Integer[] numbers={ 5, 4, 1, 3, 9, 8, 7, 2, 0};
Object[] firstSmallNumbers = (Object[])
from(digits).where(new Predicate() {
public boolean eval(Object elm) {
return
((Integer)elm) >= getContext().getIndex();
}
}).select();
This changed drastically when I finally unveiled the Quaere project at JavaZone. By then I had changed the implementation to rely solely on string parsing to have lambda expressions that resembled those we are accustomed to from LINQ.
Integer[] numbers={ 5, 4, 1, 3, 9, 8, 7, 2, 0};
Iterable<Integer> firstSmallNumbers =
takeWhile("(n, index) => n >= index");
The lambdas in the JavaZone snapshot are more compact and easier to read, but still I didn't feel too good about the implementation. The syntax is a carbon copy of the C# lambda syntax and even seasoned C# developers have difficulties groking the lambda expression syntax. Java still lack closures, and C# lambdas are very unfamiliar to the average Java developer. Another problem is that the lambda expression syntax deviates from the conventions used in "regular" queries, the lambda doesn't use any of the expression factories help the user write the query. For instance the expression part of this lambda expression could be written like this using the regular conventions.
ge("n","index")
To avoid users to learn multiple ways of writing expressions, lambda expressions have been redesigned to use fluent interfaces in Quaere. Below is the new syntax for the previous query.
Integer[] numbers = {5, 4, 1, 3, 9, 8, 7, 2, 0};
Iterable<Integer> firstSmallNumbers =
take("n").withIndexer("index").
from(numbers).when(ge("n","index"));
The syntax is a little more verbose, but IMHO this is a good tradeoff compared with the obscurity of the string based approach. Many people have been skeptical towards the use of string expressions in Quaere, I hope more people are comfortable with the new approach to the more advanced expressions.