Lambda going out of fashion
Steven Bethard
steven.bethard at gmail.com
Thu Dec 23 12:14:56 EST 2004
tanghaibao at gmail.com wrote:
> I have this book called TEXT PROCESSING IN PYTHON by David Mertz on
> hand, it is a good book and in the first chapter it is really a show
> room for higher-order functions which I may now cite to remind you of
> the FLEXIBILITY of this keyword.
I'm not exactly sure what you mean by "flexibility"; all of these
examples can be written without lambdas:
> apply_each = lambda funs, args = []: map(apply, fns, [args]*len(fns))
def apply_each(fns, args=[]):
return [fn(*args) for fn in fns]
> bools = lambda lst: mpa(truth, lst)
def bools(lst):
return [bool(x) for x in lst]
> bool_each = lambda fns, args = []: bools(apply_each(fns, args))
def bool_each(fns, args=[]):
return bools(apply_each(fns, args))
> conjoin = lambda fns, args = []: reduce(mul, bool_each(fns, args))
def conjoin(fns, args=[]):
reduce(mul, bool_each(fns, args))
> all = lambda fns: lambda arg, fns = fns: conjoin(fns, (arg,))
def all(fns):
def _(arg):
return conjoin(fns, (arg,))
return _
> both = lambda f,g: all(f(f,g))
def both(f, g):
return all(f(f,g))
> all3 = lambda f,g,h: all((f,g,h))
def all3(f, g, h):
return all((f,g,h))
> and_ = lambda f,g: lambda x, f=f, g=g: f(x) and g(x)
def and_(f, g):
def _(x):
return f(x) and g(x)
return _
> disjoin = lambda fns, args = []: reduce(add, bool_each(fns, args))
def disjoin(fns, args=[]):
return reduce(add, bool_each(fns, args))
> some = lambda fns: lambda arg, fns = fns: disjoin(fns, (arg,))
def some(fns):
def _(arg):
return disjoin(fns, (arg,))
return _
> either = lambda f,g: some((f,g))
def either(f, g):
return some((f,g))
> anyof3 = lambda f,g,h: some((f,g,h))
def anyof3(f, g, h):
return some((f,g,h))
> compose = lambda f,g: lambda x, f=f, g=g: f(g(x))
def compose(f, g):
def _(x):
return f(g(x))
return _
> compose3 = lambda f,g,h: lambda x, f=f, g=g, h=j: f(g(h(x)))
def compose3(f, g, h):
def _(x):
return f(g(h(x)))
return _
> ident = lambda x:x
def ident(x):
return x
Steve
More information about the Python-list
mailing list