fp/lambda question

Paul Rubin phr-n2002a at nightsong.com
Sat Apr 13 04:26:30 EDT 2002


Alex Martelli <aleax at aleax.it> writes:
> I like FP a lot, and I practise it -- but I eschew lambda in Python
> in most cases: it's limited and goes much against the grain of the
> language.  All it boils down to is, give your functions a name -- in
> most cases a well-chosen name will clarify your code.  E.g.,
> 
> def relatively_prime(a, b): return gcd(a, b) == 1
> 
> and so on...

Here's a fragment from a calculator app that I wrote to try out
Tkinter (the app is at http://www.nightsong.com/phr/python/calc.py).

It's a pair of tables saying what the various calculator buttons
should do to the displayed number when you push the buttons, possibly
preceded by pushing the "inverse" button (pressing "inv sin" gives you
the arcsin, etc).  Using lambdas for the functions where there weren't
ready-made built-ins seemed natural and obvious to me.  Would you really
have written separate definitions for those functions?

    unops = {'sqrt': math.sqrt,
             'sin': math.sin,
             'cos': math.cos,
             'tan': math.tan,
             'ln': math.log,
             'log': lambda x: math.log(x)/math.log(10),
             'clr x': lambda x: 0
             }

    inv_unops = {'sqrt': lambda x: x*x,
                 'sin': math.asin,
                 'cos': math.acos,
                 'tan': math.atan,
                 'ln': math.exp,
                 'log': lambda x: 10.**x,
                 'clr x': unops['clr x']
                 }



More information about the Python-list mailing list