[swift-users] Synthesized Equatable Bug?

Jon Shier jon at jonshier.com
Mon Jan 15 22:07:23 CST 2018


Thanks Dmitri. Once I looked up the total ordering for points I was able to get proper behavior.

static func < (lhs: Point, rhs: Point) -> Bool {
    return lhs.x < rhs.x || (lhs.x == rhs.x && lhs.y < rhs.y)
}


Jon

> On Jan 15, 2018, at 8:38 PM, Dmitri Gribenko <gribozavr at gmail.com> wrote:
> 
> On Mon, Jan 15, 2018 at 2:30 PM, Jon Shier via swift-users
> <swift-users at swift.org> wrote:
>> This is pretty straightforward code, so am I missing something here?
> 
> Your '<' function does not define a valid strict total order.
> 
> For
> 
> let p1 = Point(1, 1)
> let p2 = Point(0, 2)
> 
> neither of 'p1 < p2', 'p2 < p1', 'p1 == p2' is true.  This is the root cause.
> 
>> static func <= (lhs: Point, rhs: Point) -> Bool {
>>   return lhs < rhs || lhs == rhs
>> }
> 
> A faster way to compute it (with only one call to a user-defined
> comparison operator) is to return '!(rhs < lhs)', which is wat the
> standard library does, which is why you see the behavior that you are
> seeing.
> 
> Dmitri
> 
> -- 
> main(i,j){for(i=2;;i++){for(j=2;j<i;j++){if(!(i%j)){j=0;break;}}if
> (j){printf("%d\n",i);}}} /*Dmitri Gribenko <gribozavr at gmail.com>*/



More information about the swift-users mailing list