abuse of lambda question
Ben Wolfson
rumjuggler at cryptarchy.org
Thu Jun 8 00:12:42 EDT 2000
On Wed, 07 Jun 2000 03:49:31 GMT, Ben Wolfson <rumjuggler at cryptarchy.org>
wrote:
[stuff]
Ok, I got it working now. The complete lambdabuse.py file, so far, is:
"""
Functions to aid in grossly abusing lambdas. This will greatly help Python
develop as a langauge.
For example, if you wanted to get every other element of a list in two
different lists, you *could*
write something nice and clear, like:
def everyother(list):
evens, odds= [],[]
putineven = 1
for e in list:
if putineven:
evens.append(e)
putineven = 0
else:
odds.append(e)
putineven = 1
return evens, odds
which can be called as everyother(range(20)), or you could write something
completely unreadable,
like:
everyother = lambda l, evens, odds, app=lambda a,e: lambda
a=a,e=e:a.append(e): Compose(Apply(map, lambda e, evens=list(evens),
odds=list(odds), l=l,app=app: If(l.index(e)%2==0, app(evens,e),
app(odds,e)), l), Return(None, evens, odds))
which *must* be called as everyother(range(20),[],[]).
The choice is obvious.
"""
def For(count, fct, *args, **kwargs):
for i in range(count):
fct(i,*args,**kwargs)
def While(cond, fct, *args, **kwargs):
while cond():
fct(*args, **kwargs)
def Compose(*args):
for f in args[:-1]:
f()
return args[-1]()
def Return(index, *args):
if index is not None:
return lambda a=args[index]: a
return lambda a=args:a
def Apply(f, *args, **kwargs):
return lambda f=f, a=args, k=kwargs: apply(f,a,k)
def If(cond, t, f):
if callable(cond):
cond = cond()
if cond:
return t()
return f()
__everyother = lambda l, evens, odds, app=lambda a,e:\
lambda a=a,e=e:a.append(e): Compose(
Apply(map, \
lambda e, evens=list(evens), odds=list(odds), l=l,app=app: \
If(l.index(e)%2==0, app(evens,e), app(odds,e)), l),\
Return(None, evens, odds))
def Elif(cond, t, f, *cond_elifs):
conditions, eliffuncs = __everyother(list(cond_elifs),[],[])
#must be a list to use .index()
if callable(cond):
cond=cond()
if cond:
return t()
else:
for i in range(len(conditions)):
if conditions[i]():
return eliffuncs[i]()
return f()
def Map(f, *args):
return lambda f=f, args=args: map(f, *args)
def Print(a):
def p(a=a):
print a
return p
##an example. For a group of lists l1...ln,
##__unmapNone(map(None, l1,...,ln)) == (l1,...,ln)
__unmapNone=lambda l, result: Compose(
Apply(For, len(l), lambda c, a: a.append([]), result),
Map(lambda a,r=result: For(len(a), \
lambda c,a,r: r[c].append(a[c]), a, r),l),
Return(0,result))
--
Barnabas T. Rumjuggler
So witless did these ideas strike me as being, so sweeping and pompous the
way they were expressed, that I associated them immediately with
literature.
-- Jorge Luis Borges, "The Aleph"
More information about the Python-list
mailing list