News from Jun 25, 2008

  2008/06/25
Added python-like list comprehensions and tuples
Last changed: Jun 25, 2008 17:50 by Terence Parr

I realized that we need the notion of a tuple like Python. List [1,2] is fundamentally an ordered thing not an aggregate of two elements. A tuple (1,2) treats those as separate elements whereas I can think of the list as one thing if I pass it to a function. A tuple is not accessed like a list and really is used to only hold multiple values. I could use this for parallel assignment, but I don't have that and I'm not sure I want it. I decided that we really needed tuples so that we can do parallel iteration using closures:

	list a = [5, 9, 2, 120, 81];
	list b = [1, 8, 34, 92, 4];
	list c = (a,b):{int x, int y | return x*y;};
	println(c);

which prints:

[5, 72, 68, 11040, 324]

The a and b get mapped to the arguments of closure x and y. Greg Benson, another professor here at the University of San Francisco, suggested that that was pretty unintuitive notation. He persuaded me that the Python syntax is not bad so I added it as a special case of the list literal:

list c = [x*y for int x in a, int y in b];

Underneath, of course, it is implemented simply as the above closure applied to a tuple. Here is a set of tests:

list a = [5, 9, 2, 120, 81];
list b = [1, 8, 34, 92, 4];
//(a,b):{int x, int y | int k=x*2; return x*y;};
list c = [x*y for int x in a, int y in b];
println(c);
list d = [x*y for int x in a, int y in b where x<10];
println(d);

println( [x for int x in a where x>10] );

println( [(x,y) for int x in a, int y in b] );

which emits:

[5, 72, 68, 11040, 324]
[5, 72, 68]
[120, 81]
[(5, 1), (9, 8), (2, 34), (120, 92), (81, 4)]
Posted at 25 Jun @ 5:49 PM by Terence Parr | 0 Comments

June 2008
Sun Mon Tue Wed Thu Fri Sat
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30          

Aug 30, 2008
Feb 08, 2008