C#3.0 and lambdas

Roel Schroeven rschroev_nospam_ml at fastmail.fm
Wed Sep 21 10:55:24 EDT 2005


Christophe schreef:
> Steve Holden a écrit :
> 
>> Christophe wrote:
>>
>>> Serhiy Storchaka a écrit :
>>>
>>>> Roel Schroeven wrote:
>>
>>
>> [...]
>>
>>>>> or
>>>>>
>>>>> def drawline(p1, p2):
>>>>>    # draw a line from p1[0], p1[1] to p2[0], p2[1]
>>>>>    foo(p1[0], p1[1])
>>>>>    bar(p2[0], p2[1])
>>>>
>>>>
>>>>
>>>>
>>>> def drawline(p1, p2):
>>>>     # draw a line from p1 to p2
>>>>     foo(*p1)
>>>>     bar(*p2)
>>>>
>>>
>>>
>>> That one is stupid. I don't see how you can make it work without some
>>> global storing the p1 information in foo which I would consider as
>>> very ugly code.
>>
>>
>>
>> In which case perhaps you should actually try the code. Then once you
>> realise it works you can start to figure out why :-). Hint: f(*p1)
>> appears as len(p1) separate arguments to the called function.
> 
> 
> You should also notice that foo knows the starting point of the line but
> not the ending point and so it can't draw the line. On the other hand,
> bar knows the end point but not the starting point so it can't do the
> job either.

It was just an example of tuples as arguments to a function and doing
something with the values of the tuples in the function itself. Even so,
many graphical environments offer MoveTo(x, y) and LineTo(x, y) or
equivalents. MoveTo moves some internal cursor to the specified position
without drawing a line; LineTo draws a line from the stored cursor
position to the specified position and moves the internal cursor to that
 new position.

> And what about a function which computes the line length ?

That would have been a better example indeed, since the *p1 trick
doesn't work there.

def euclidian_distance((x1, y1), (x2, y2)):
    return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)

That's a lot nicer, I think, than this:

def euclidian_distance(p1, p2):
    return math.sqrt((p2[0] - p1[0])**2 + (p2[1] - p1[1])**2)


-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

Roel Schroeven



More information about the Python-list mailing list