Three-way comparison

In computer science, a three-way comparison takes two values A and B belonging to a type with a total order and determines whether A < B, A = B, or A > B in a single operation, in accordance with the mathematical law of trichotomy.

It can be implemented in terms of a function (such as strcmp in C), a method (such as compareTo in Java), or an operator (such as the spaceship operator <=> in Perl, PHP and C++).

Machine-level computation

Many processors have instruction sets that support such an operation on primitive types. Some machines have signed integers based on a sign-and-magnitude or ones' complement representation (see signed number representations), both of which allow a differentiated positive and negative zero. This does not violate trichotomy as long as a consistent total order is adopted: either −0 = +0 or −0 < +0 is valid. Common floating point types, however, have an exception to trichotomy: there is a special value "NaN" (Not a Number) such that x < NaN, x > NaN, and x = NaN are all false for all floating-point values x (including NaN itself).

High-level languages

Abilities

In C, the functions strcmp and memcmp perform a three-way comparison between strings and memory buffers, respectively. They return a negative number when the first argument is lexicographically smaller than the second, zero when the arguments are equal, and a positive number otherwise. This convention of returning the "sign of the difference" is extended to arbitrary comparison functions by the standard sorting function qsort, which takes a comparison function as an argument and requires it to abide by it.

In Perl (for numeric comparisons only, the cmp operator is used for string lexical comparisons), PHP (since version 7), Ruby, and Apache Groovy, the "spaceship operator" <=> returns the values −1, 0, or 1 depending on whether A < B, A = B, or A > B, respectively. The Python 2.x cmp(removed in 3.x), OCaml compare, and Kotlin compareTo functions compute the same thing. In the Haskell standard library, the three-way comparison function compare is defined for all types in the Ord class; it returns type Ordering, whose values are LT (less than), EQ (equal), and GT (greater than):[1]

data Ordering = LT | EQ | GT

Many object-oriented programming languages have a three-way comparison function, which performs a three-way comparison between the object and another given object. For example, in Java, any class that implements the Comparable interface has a compareTo method which either returns a negative integer, zero, or a positive integer, or throws a NullPointerException (if one or both objects are null). Similarly, in the .NET framework, any class that implements the IComparable interface has such a CompareTo method. In C++, any class that can be three-way compared can be a parameter to instances of std::compare_three_way, std::strong_order, std::weak_order, or std::partial_order.

Since Java version 1.5, the same can be computed using the Math.signum static method if the difference can be known without computational problems such as arithmetic overflow mentioned below. Many computer languages allow the definition of functions so a compare(A,B) could be devised appropriately, but the question is whether or not its internal definition can employ some sort of three-way syntax or else must fall back on repeated tests.

When implementing a three-way comparison where a three-way comparison operator or method is not already available, it is common to combine two comparisons, such as A = B and A < B, or A < B and A > B. In principle, a compiler might deduce that these two expressions could be replaced by only one comparison followed by multiple tests of the result, but mention of this optimization is not to be found in texts on the subject.

In some cases, three-way comparison can be simulated by subtracting A and B and examining the sign of the result, exploiting special instructions for examining the sign of a number. However, this requires the type of A and B to have a well-defined difference. Fixed-width signed integers may overflow when they are subtracted, floating-point numbers have the value NaN with undefined sign, and character strings have no difference function corresponding to their total order. At the machine level, overflow is usually tracked and can be used to determine order after subtraction, but this information is usually unavailable to higher-level languages.

In one case of a three-way conditional provided by the programming language, Fortran's now-deprecated three-way arithmetic IF statement considers the sign of an arithmetic expression and offers three labels to jump to according to the sign of the result:

     IF (expression) negative,zero,positive

The common library function strcmp in C and related languages is a three-way lexicographic comparison of strings; however, these languages lack a general three-way comparison of other data types.

Spaceship operator

The three-way comparison operator or "spaceship operator" for numbers is denoted as <=> in Perl, Ruby, Apache Groovy, PHP, Eclipse Ceylon, and C++, and is called the spaceship operator.[2]

In C++, the C++20 revision adds the spaceship operator <=>, which returns a value that encodes whether the 2 values are equal, less, greater, or unordered and can return different types depending on the strictness of the comparison.[3]

The name's origin is due to it reminding Randal L. Schwartz of the spaceship in an HP BASIC Star Trek game.[4] Another coder has suggested that it was so named because it looked similar to Darth Vader's TIE fighter in the Star Wars saga.[5]

Example in PHP:

echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1

Example in C++:

1 <=> 1; // evaluates to std::strong_ordering::equal
1 <=> 2; // evaluates to std::strong_ordering::less
2 <=> 1; // evaluates to std::strong_ordering::greater

Composite data types

Three-way comparisons have the property of being easy to compose and build lexicographic comparisons of non-primitive data types, unlike two-way comparisons.

Here is a composition example in Perl.

sub compare($$) {
    my ($a, $b) = @_;
    return $a->{unit} cmp $b->{unit}
        || $a->{rank} <=> $b->{rank}
        || $a->{name} cmp $b->{name};
}

Note that cmp, in Perl, is for strings, since <=> is for numbers. Two-way equivalents tend to be less compact but not necessarily less legible. The above takes advantage of short-circuit evaluation of the || operator, and the fact that 0 is considered false in Perl. As a result, if the first comparison is equal (thus evaluates to 0), it will "fall through" to the second comparison, and so on, until it finds one that is non-zero, or until it reaches the end.

In some languages, including Python, Ruby, Haskell, etc., comparison of lists is done lexicographically, which means that it is possible to build a chain of comparisons like the above example by putting the values into lists in the order desired; for example, in Ruby:

[a.unit, a.rank, a.name] <=> [b.unit, b.rank, b.name]

In C++:

std::tie(a.unit, a.rank, a.name) <=> std::tie(b.unit, b.rank, b.name)

See also

References

  1. ^ Data.Ord
  2. ^ "Math::Complex". Perl Programming Documentation. Retrieved 26 September 2014.
  3. ^ Herb Sutter proposed adding a three-way comparison operator to the C++ standard with the <=> syntax, in a paper entitled "Consistent Comparison". See "Consistent Comparison" It was successfully merged into the C++20 draft in November 2017.
  4. ^ "Spaceship history (was Re: [dart-misc] DEP meeting notes)".
  5. ^ "Super Spaceship Operator". 2000-12-08. Retrieved 2014-08-06.

Read other articles:

Daniel Braaten Informasi pribadiNama lengkap Daniel Omoya BraatenTanggal lahir 25 Mei 1982 (umur 41)Tempat lahir Oslo, NorwegiaTinggi 1,84 m (6 ft 0 in)Posisi bermain GelandangInformasi klubKlub saat ini ToulouseNomor 25Karier junior0000–2000 SkeidKarier senior*Tahun Tim Tampil (Gol)2000–2004 Skeid 102 (22)2004–2007 Rosenborg 63 (12)2007–2008 Bolton Wanderers 6 (1)2008– Toulouse 134 (12)Tim nasional‡2003–2004 Norwegia U-21 2 (0)2004– Norwegia 42 (2) * Pena...

 

هذه المقالة يتيمة إذ تصل إليها مقالات أخرى قليلة جدًا. فضلًا، ساعد بإضافة وصلة إليها في مقالات متعلقة بها. (مارس 2023) كأس السوبر( الفاتيكان ) Super Coppa (Vatican City) هي كأس سنوية لمباراة كرة القدم المحلية لفرق مدينة الفاتيكان. عْقد كأس السوبر الافتتاحي عام 2005.[1] يتنافس على كأس السو�...

 

Wakil Bupati MadiunPetahanaH. Hari Wuryanto, S.H., M.Ak.sejak 24 September 2018Masa jabatan5 tahunDibentuk2003Pejabat pertamaMuhtaromSitus webmadiunkab.go.id Berikut ini adalah daftar Wakil Bupati Madiun dari masa ke masa. No Wakil Bupati Mulai Jabatan Akhir Jabatan Prd. Ket. Bupati 1 H.MuhtaromS.Sos. 2003 2008 1   H.KRH. Djunaedi MahendraS.H., M.Si. 2 Drs. H.IswantoM.Si. 23 Juli 2008 23 Juli 2013 2   H.MuhtaromS.Sos. Jabatan kosong 23 Juli 2013 3 Agustus 2013 - Soekardi(Pelaks...

Disambiguazione – Stati Uniti, USA, United States e States rimandano qui. Se stai cercando altri significati, vedi Stati Uniti (disambigua), USA (disambigua), United States (disambigua) o States (disambigua). Stati Uniti d'America (dettagli) (dettagli) In God We Trust (In Dio noi confidiamo) Stati Uniti d'America - Localizzazione Dati amministrativiNome ufficialeUnited States of America Lingue ufficialiNessuna a livello federale (de iure)[N 1] Inglese (d...

 

Mathias NorsgaardInformationsNom de naissance Mathias Norsgaard JørgensenNaissance 5 mai 1997 (26 ans)SilkeborgNationalité danoiseÉquipe actuelle Movistar TeamÉquipes non-UCI 2005-2011Silkeborg IF Cykling2012-2013Herning Cykle KlubÉquipes UCI 2014-2015Team Kelberg-Roskilde Junior2016SEG Racing Academy2017Giant-Castelli2018Riwal CeramicSpeed2019Riwal Readynez2020-Movistar TeamPrincipales victoires Championnats Champion du Danemark du contre-la-montre 2022modifier - modifier le code -...

 

Eurovision Song Contest 2004Country IsraelNational selectionSelection processArtist: Internal SelectionSong: Kdam Eurovision 2004Selection date(s)Artist: 13 November 2003Song: 5 February 2004Selected entrantDavid D'OrSelected songLeha'aminSelected songwriter(s)David D'OrOfer MeiriEhud ManorFinals performanceSemi-final resultFailed to qualify (11th)Israel in the Eurovision Song Contest ◄2003 • 2004 • 2005► Israel participated in the Eurovision Song C...

Questa voce sull'argomento stagioni delle società calcistiche italiane è solo un abbozzo. Contribuisci a migliorarla secondo le convenzioni di Wikipedia. Segui i suggerimenti del progetto di riferimento. Voce principale: Associazione Calcio Ancona. AnconitanaStagione 1945-1946Sport calcio Squadra Anconitana Allenatore Achille Piccini Divisione Nazionale11º (Centro-Sud) 1944-45 1946-47 Si invita a seguire il modello di voce Questa voce raccoglie le informazioni riguardanti la Uni...

 

Metropolitan Opera House di Lincoln Center for the Performing Arts, dilihat dari Lincoln Center Plaza Metropolitan Opera (the Met) adalah sebuah perusahaan opera yang terletak di New York City. Awalnya didirikan tahun 1880,[1] perusahaan ini mengadakan pertunjukan pertamanya pada 22 Oktober 1883. Perusahaan ini dioperasikan oleh asosiasi nirlaba Metropolitan Opera Association, dengan Peter Gelb sebagai manajer umumnya. Direktur musiknya ialah James Levine. The Met mengadakan pertunjuk...

 

Chemicals that result in blistering and skin irritation and damaging Blister agents are named for their ability to cause large, painful water blisters on the bodies of those affected. Soldier with moderate mustard gas burns sustained during World War I showing characteristic bullae on neck, armpit and hands Part of a series onChemical agents Lethal agents Blood Cyanogen chloride (CK) Hydrogen cyanide (AC) Arsine (SA) Blister Ethyldichloroarsine (ED) Methyldichloroarsine (MD) Phenyldichloroars...

1947 aviation accident Pan Am Flight 121Lockheed L-049 Constellation in PAN AM livery, similar to the crash aircraft.AccidentDateJune 19, 1947 (1947-06-19)SummaryEngine fireSiteSyrian Desert, 4 miles (6.4 km) from Mayadin, SyriaAircraftAircraft typeLockheed L-049 ConstellationAircraft nameClipper EclipseOperatorPan American World AirwaysRegistrationNC88845Flight originKarachi Civil Airport, Karachi, British RajDestinationIstanbul, TurkeyOccupants36Passengers26Crew10Fa...

 

Sceaux 行政国 フランス地域圏 (Région) イル=ド=フランス地域圏県 (département) オー=ド=セーヌ県郡 (arrondissement) アントニー郡小郡 (canton) 小郡庁所在地INSEEコード 92071郵便番号 92330市長(任期) フィリップ・ローラン(2008年-2014年)自治体間連合 (fr) メトロポール・デュ・グラン・パリ人口動態人口 19,679人(2007年)人口密度 5466人/km2住民の呼称 Scéens地理座標 北緯48度4...

 

Міністерство оборони України (Міноборони) Емблема Міністерства оборони та Прапор Міністерства оборони Будівля Міністерства оборони у КиєвіЗагальна інформаціяКраїна  УкраїнаДата створення 24 серпня 1991Попередні відомства Міністерство оборони СРСР Народний комісарі...

2020年夏季奥林匹克运动会波兰代表團波兰国旗IOC編碼POLNOC波蘭奧林匹克委員會網站olimpijski.pl(英文)(波兰文)2020年夏季奥林匹克运动会(東京)2021年7月23日至8月8日(受2019冠状病毒病疫情影响推迟,但仍保留原定名称)運動員206參賽項目24个大项旗手开幕式:帕维尔·科热尼奥夫斯基(游泳)和马娅·沃什乔夫斯卡(自行车)[1]闭幕式:卡罗利娜·纳亚(皮划艇)&#...

 

Lentille gravitationnelle pleine. Une étoile à préon est un type d’étoile compacte hypothétique constituée de préons, un groupe de particules subatomiques elles-mêmes hypothétiques. Les étoiles à préon devraient avoir une densité énorme, supérieure à 1023 kg/m3. Il s’agit d’un chiffre intermédiaire entre les étoiles à quarks et les trous noirs. Une étoile à préon d’une masse comparable à celle de la Terre aurait ainsi la taille d’une balle de tennis. Les étoi...

 

Canadian actor Joshua Odjick and other cast of The Swarm on the red carpet at the Berlinale 2023 (first from the right) Joshua Odjick is a Canadian actor from Kitigan Zibi, Quebec.[1] He is most noted for his performance as Pasmay in the 2021 film Wildhood, for which he won the Canadian Screen Award for Best Supporting Actor at the 10th Canadian Screen Awards in 2022,[2] and the Vancouver Film Critics Circle award for Best Supporting Actor in a Canadian Film at the Vancouver F...

Mass shooting in Norway 2022 Oslo shootingThe police blockade at the location where the shooting took placeLondon PubLondon Pub (Oslo)Show map of OsloLondon PubLondon Pub (Norway)Show map of NorwayLondon PubLondon Pub (Europe)Show map of EuropeLocationOslo, NorwayCoordinates59°54′55″N 10°44′26″E / 59.91528°N 10.74056°E / 59.91528; 10.74056Date25 June 2022 (CEST UTC+02:00)Attack typeMass shootingWeapons MP 40 submachine gun[1] Luger P08 pistol[2&...

 

Sazeman-e Ettela'at va Amniyat-e KeshvarInformasi lembagaDibentuk1957Dibubarkan1979Lembaga penggantiKantor Intelijen Perdana MenteriKantor pusatTeheranPegawai5000 pada puncaknya[1]MenteriIntelijenPejabat eksekutifTeymur Bakhtiar (Pertama)Nasser Moghadam (Terakhir) SAVAK (Persia: ساواک‎, singkatan dari سازمان اطلاعات و امنیت کشور Sāzemān-e Ettelā'āt va Amniyat-e Keshvar, secara harfiah Organisasi Keamanan dan Intelijen Nasional) adalah dinas po...

 

الإمام  القاضي الفاضل معلومات شخصية اسم الولادة عبد الرحيم البيساني الميلاد 2 أبريل 1135   عسقلان  الوفاة 25 يناير 1200 (64 سنة)   القاهرة  الحياة العملية المهنة شاعر،  وأديب،  وكاتب،  وسياسي  اللغات العربية  تعديل مصدري - تعديل   عبد الرحيم البيساني، ال�...

Group of baseball parks in the New York City borough of Brooklyn This article is about the baseball stadiums in Brooklyn, New York. For the stadium in Indianapolis, see Washington Park (Indianapolis). For the stadium in Los Angeles, see Washington Park (Los Angeles). Washington ParkEntrance to the second incarnation of Washington Park, 1911Washington ParkLocation in New York CityShow map of New York CityWashington ParkLocation within the State of New YorkShow map of New YorkWashington ParkLoc...

 

Stefan Bradl pada tahun 2010 Stefan Bradl (lahir 29 November 1989) merupakan seorang pembalap MotoGP berkebangsaan Jerman yang saat ini membalap untuk tim Honda LCR. Dia merupakan juara dunia kelas Moto2 pada tahun 2011. Tahun 2019, Bradl bergabung dengan Repsol Honda sebagai test rider menggaantikan Jorge Lorenzo Biografi Sebelumnya dia mulai membalap di kelas 125cc pada tahun 2005 dan 2006 dia menjadi sebagai seorang wildcard rider untuk tiga seri bersama KTM. Bradl mendapat tawaran dari Al...