ACCEPTABLE?: List Comprehensions?

Reinier Zwitserloot reinier at
Mon Mar 16 17:54:06 PDT 2009


Scala and Python both have list comprehensions. They both implement  
them according to my sketch: 1 generator expression, filters AFTER the  
source, and multiple sources allowed. They don't allow multiple  
generator expressions and they don't allow you to put ifs on the  
generators (you put them on the sources). Exactly like the syntax I  
sketched in an earlier mail to coin-dev. It seems clear then that the  
main use-case appears to be nested fors (multiple source expressions),  
and not turning a list of 3 elements into something with more than that.


The only saving grace here is that in both scala and python, you can  
take a List<Tuple(String, String)> and turn them into a List<String>  
by unpacking the tuples, fairly easily. This is slightly more  
complicated in java, but not terribly so *IF* we have list literals:

public static <T> List<T> compress(List<List<T>> input) {
    //implementation obvious

compress([ [a, a] for int a : intList]); //turns [1, 2, 3] into [1, 1,  
2, 2, 3, 3].

I don't suggest adding it to this proposal. Just highlighting that, if  
certain people really are stumped without this feature, they can solve  
it with minimal effort and 1 static import, which is a lot better than  
nothing at all. I say: err on the side of caution. If the above idiom  
becomes well-used, we can always add a syntax for multiple generator  
expressions at some later point in time.

  --Reinier Zwitserloot

On Mar 16, 2009, at 21:48, Paulo Levi wrote:

> I dunno.
> The major line reduction win is in the nested fors example, but most  
> of the fors i make with a list output are not nested. I would just  
> like that this proposal also adapts to the simple zip or multi-map  
> usage.
> Lets see if i understand it:
> Simple copy:
> List<Integer> out = [x for x : in]
> Simple map:
> List<Integer> out = [x+valueToAdd for x : in]
> Multi-map :
> List<Integer> out = [x+valueToAdd, x+3 for x : in] (output list.size  
> = in.size * 2)
> List<Integer> out = [x+valueToAdd if x % 2 == 0, x+3 if x % 2 != 0  
> for x : in]
> Zip:
> List<Integer> out = [x+valueToAdd, y+3 for x : in, y : in2]
> List<Integer> out = [x+valueToAdd if x % 2 == 0, y+3 if x % 2 == 0  
> for x : in, y : in2]
> Nested fors (only 1 condiction allowed):
> [ a + b + c, if a > 5 && c < 2,  for a : intList1, for b : intList,  
> for c : intList]
> The nested for is the most bizarre and unusual example of all.
> I see why you put the condition after the for, but i think that is a  
> little less readable.
> If you see the nested fors example you see i'm contracting myself,  
> viz ";" and ",".
> I leave the field to the experts, but please make the main usecase  
> the easiest.

More information about the coin-dev mailing list