squared functions--most Pythonic way?

Janto Dreijer janto_d at hotmail.com
Fri Jun 28 11:14:41 EDT 2002


I don't have time to refine this, so I'm just throwing it out there. (I've
already spent 20min trying to post this through google)

def addNumbers(k):
    def f(x):
        a = addNumbers(x + k)
        a.val = x+k
        return a
    return f

>>> addNumbers(9)(5)(2)(4)(6).val
26

ooooh!!! Now _that's_ pretty :-)

Now if only I could figure out how to use __repr__() so I don't need that
".val"
It also fails when passed only one number. i.e addNumbers(5)
Help?


"Giorgi Lekishvili" <gleki at gol.ge> wrote in message
news:3D1C207A.74F24164 at gol.ge...
> One of the biggest advantages of Python is its nice and elegand mixture of
> procedural, OO and functional programming... I would prefer lambda stile
as the
> most concise, but it is a matter of personal "phylosophy";)
>
> Grtz,
> Giorgi
>
> Sean 'Shaleh' Perry wrote:
>
> > >
> > > functional programming:
> > >
> > >     # with an internal named function
> > >     def fsquare(f):
> > >         def f2(x):
> > >             return f(x)**2
> > >         return f2
> > >
> >
> > this seems to be the most pythonic (lambda is not the preferred approach
> > usually).
> >
> > Of course someone will mention taking this to the next step with a
compose()
> > function which take f(x) and g(x).
>





More information about the Python-list mailing list