Arithmetic sequences in Python

Tom Anderson twic at urchin.earth.li
Sat Jan 21 10:33:41 EST 2006


On Fri, 20 Jan 2006, it was written:

> aleax at mail.comcast.net (Alex Martelli) writes:
>
>>> How would you make a one-element list, which we'd currently write as 
>>> [3]? Would you have to say list((3,))?
>>
>> Yep.  I don't particularly like the "mandatory trailing comma" in the 
>> tuple's display form, mind you, but, if it's good enough for tuples, 
>> and good enough for sets (how else would you make a one-element set?),
>
> If you really want to get rid of container literals, maybe the best way 
> is with constructor functions whose interfaces are slightly different 
> from the existing type-coercion functions:
>
>    listx(1,2,3)  => [1, 2, 3]
>    listx(3)      => [3]
>    listx(listx(3)) => [[3]]
>    dictx((a,b), (c,d))  => {a:b, c:d}
>    setx(a,b,c)   => Set((a,b,c))
>
> listx/dictx/setx would be the display forms as well as the constructor forms.

Could these even replace the current forms? If you want the equivalent of 
list(sometuple), write list(*sometuple). With a bit of cleverness down in 
the worky bits, this could be implemented to avoid the apparent overhead 
of unpacking and then repacking the tuple. In fact, in general, it would 
be nice if code like:

def f(*args):
 	fondle(args)

foo = (1, 2, 3)
f(*foo)

Would avoid the unpack/repack.

The problem is that you then can't easily do something like:

mytable = ((1, 2, 3), ("a", "b", "c"), (Tone.do, Tone.re, Tone.mi))
mysecondtable = map(list, mytable)

Although that's moderately easy to work around with possibly the most 
abstract higher-order-function i've ever written:

def star(f):
 	def starred_f(args):
 		return f(*args)
 	return starred_f

Which lets us write:

mysecondtable = map(star(list), mytable)

While we're here, we should also have the natural complement of star, its 
evil mirror universe twin:

def bearded_star(f):
 	def bearded_starred_f(*args):
 		return f(args)
 	return bearded_starred_f

Better names (eg "unpacking" and "packing") would obviously be needed.

tom

-- 
I might feel irresponsible if you couldn't go almost anywhere and see
naked, aggressive political maneuvers in iteration, marinating in your
ideology of choice. That's simply not the case. -- Tycho Brahae



More information about the Python-list mailing list