lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]



On 27-Aug-05, at 11:15 AM, Adrian Sietsma wrote:

i agree, but i still like Roberto's option of comparison operators returning the mathing object, instead of "true" - that matches and/or behaviour.


I think it has its charm; I was playing with that a while ago when I was first thinking about max and min operators.

The fact that you can't define __lt on booleans is a minor flaw, but it leads to the issue that you cannot define == to work the same way. That is, a == b cannot return a if the objects are equal, because that would then mean that

  nil == nil

and

  false == false

were nil and false, respectively.

So == cannot be consistent with < and <=, which is a slightly more serious blemish.

The most serious issue, which also plagues C programs and is the reason that gcc chose to implement min and max operators (<? and >? if I recall correctly) is that you cannot open code min and max without evaluating the arguments twice. So there is nothing wrong with

  a < b and a or b

But something desperately wrong with

  f(a) < f(b) and f(a) or f(b)

This would not be a problem with

  f(a) min f(b)

and is probably the single best argument for having the operators.

Finally, I prefer min and max because there are types where min and max cannot be defined in terms of < or <=. In those cases, I would prefer to have an operator backed by a metamethod; failing that, I'm happy to use a function backed by a metamethod, which is what I actually do in practice, regardless of speed issues, because I like the self-documentation.

[Note]
Depending on what you think numeric min and max should return if one of the arguments is a NaN, numeric min and max can also be difficult to properly implement in terms of <. However, I was thinking more of partial order relationships like subset. My preference is that min of two sets is their intersection and max is their union; that cannot be defined in terms of a subset predicate. If you prefer the definition that min/max of two sets returns nil if the sets are not comparable then you can, but it looks different and arguably suffers from an efficiency problem:

  a <= b and a or b <= a and b

I'm going to shut up about this issue now. :)