On writing Python one-liners.
pythonlambdafunctional-programmingone-liners
Abstraction: Using lambdas to encode any Python program as one line
Key points:
- Variable assignments can be eliminated by converting locals into function arguments passed to immediately-invoked lambdas
- Local function definitions are replaced with lambda arguments:
(lambda g, h, n: g(h(g(h(n)))))(lambda n: 2n+1, lambda n: 3n-2, n) - Recursion requires self-application: rewrite
fact(n)asurfact(f, n)wherefis passed as itself, enablingf(f, n-1) - Lazy evaluation for conditionals is achieved by wrapping branches in zero-argument lambdas:
{True: lambda: 1, False: lambda: n*f(f, n-1)}[n<=1]() - The technique can theoretically compile any Python subset into a single expression, but the result is unmaintainable
Connections: Functional Programming · Lambda Calculus · Python Programming
Source: http://blog.sigfpe.com/2008/09/on-writing-python-one-liners.html