a = b = 1 just syntactic sugar?

Ed Avis ed at membled.com
Fri Jun 6 08:27:59 CEST 2003


Steven Taschuk <staschuk at telusplanet.net> writes:

>>[...] (Of course, a multi-line lambda which used indentation to show
>>the function body would be welcome...)
>
>That sounds a lot like def to me.
> 
>Of course, you probably want the def statement to be an expression,
>so you can write it inline.  That's what I can't see playing well
>with indentation syntax.

Point taken.

>I'm not sure I understand the difficulty; I'd be interested to see
>an example of the code you wanted to write but couldn't.

On second thoughts I think it was a kind of unification that would
return a function to turn x into y, or return None if x and y could
not be unified.

    # Returns a function that changes x to y, or None if such a change
    # is not possible.
    #
    def maybe_unify(x, y):
      if x == y:
        # Already identical, unification function does nothing
        return lambda X: pass
      elif x == None:
        # x is unspecified, so can be changed to y
        return lambda X: X = y
      else:
        # Cannot unify.
        return None

(Note: I don't claim this is some general unification algorithm, it is
one-sided and in any case just an example.)  In the actual code, x and
y were data structures that were unified recursively, and I tried to
write a kind of function composition to build a larger unification
function from the results of recursive calls.

Another way to do the job would have been to have the function return
a copy of the structure, but I needed to modify it in-place.

I realize that the above code wouldn't work anyway, even if assignment
were allowed in lambda expressions, because of course the X parameter
to the lambda function is passed by value and any assignment to it
won't affect the caller.  But I'm pretty sure the code I wanted to
write had something like X[5] = y[5], which would work.

(Hmm, that would fall foul of the scoping rules, since y is a local
variable to unify_maybe.  When I wrote this code I did not have much
experience with Python and hadn't got fully used to the scoping
rules.  So perhaps it's not a good example.)

-- 
Ed Avis <ed at membled.com>




More information about the Python-list mailing list