C#3.0 and lambdas
Christophe
chris.cavalaria at free.fr
Wed Sep 21 17:08:14 CEST 2005
Steve Holden a écrit :
> Christophe wrote:
>
>> 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.
>>
> This is rubbish.
>
> foo(*p1)
>
> is *exactly* equivalent to
>
> foo(p1[0], p1[1])
>
> and similarly
>
> bar(p2)
>
> is *exactly* equivalent to
>
> bar(p2[0], p2[1])
>
> and consequently the second version of drawline is exactly equivalent to
> the first. So, if the second one is useless then so is the first.
Well, sorry about that but you are perfectly right. The point I was
trying to defend though was that such construct is very uncommon. It
isn't always possible to unpack the tuples like that because you usually
need all the info at once.
>> And what about a function which computes the line length ?
>
>
> I'm not sure what point you are trying to make here. Can you explain?
As I said, the point was that in that specific case, you can do it like
that, but most of the time you need the unpack info for all the data in
the same function. For example to compute the line length.
def length((x1,y1),(x2,y2)):
return math.hypot(x1-x2,y1-y2)
No unpack trick ( that I know of ) can be used here. You only have 1 way
to do it without the unpack in function parameters syntax :
def length(p1, p2):
x1, y1 = p1
x2, y2 = p2
return math.hypot(x1-x2,y1-y2)
More information about the Python-list
mailing list