a = b = 1 just syntactic sugar?
Ed Avis
ed at membled.com
Sat Jun 7 18:16:08 EDT 2003
junk <junk at geekabytes.net> writes:
>If you care, I wrote a little function that will return the current
>function within a block. This means, you can have anonymous recursive
>functions like this:
>
>import selfref
>factorial = lambda x: ((x==0)*1) or (x * selfref.myself(x-1))
>
>Here is the code:
>
>def myself(*args):
> prevFrame = sys._getframe(1)
> myOwnCode = prevFrame.f_code
> myOwnFuncObj = new.function(myOwnCode, globals())
> return myOwnFuncObj(*args)
>
>The only thing this doesn't do is to capture default arguments!!!
I suppose you could generalize it to not only the containing function
but ones above that, for defining mutually recursive functions.
Suppose 'myself2' is like 'myself' except it does sys._getframe(2).
f = lambda x: ((x==0)*1) or (1 + (lambda y: selfref.myself2(y-2))(x))
Sorry that it's too late at night for me to think up a more useful
example of mutual recursion :-P.
It would be neater if the language supported this directly, like ML's
'fun'. (ML has 'fn x => x + 1' for defining a simple function, and
'fun f x => 1 + f (x-1)' for giving a name to the function so it can
call itself recursively. Python's 'lambda' is like 'fn' but there is
no equivalent of 'fun'.) But I don't hold out much hope :-(.
--
Ed Avis <ed at membled.com>
More information about the Python-list
mailing list