Syntactic sugar

In computer science, syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language "sweeter" for human use: things can be expressed more clearly, more concisely, or in an alternative style that some may prefer. Syntactic sugar is usually a shorthand for a common operation that could also be expressed in an alternate, more verbose, form: The programmer has a choice of whether to use the shorter form or the longer form, but will usually use the shorter form since it is shorter and easier to type and read.

For example, many programming languages provide special syntax for referencing and updating array elements. Abstractly, an array reference is a procedure of two arguments: an array and a subscript vector, which could be expressed as get_array(Array, vector(i,j)). Instead, many languages provide syntax such as Array[i,j]. Similarly an array element update is a procedure consisting of three arguments, for example set_array(Array, vector(i,j), value), but many languages also provide syntax such as Array[i,j] = value.

A construct in a language is syntactic sugar if it can be removed from the language without any effect on what the language can do: functionality and expressive power will remain the same.

Language processors, including compilers and static analyzers, often expand sugared constructs into their more verbose equivalents before processing, a process sometimes called "desugaring".

Origins

The term syntactic sugar was coined by Peter J. Landin in 1964 to describe the surface syntax of a simple ALGOL-like programming language which was defined semantically in terms of the applicative expressions of lambda calculus,[1][2] centered on lexically replacing λ with "where".

Later programming languages, such as CLU, ML and Scheme, extended the term to refer to syntax within a language which could be defined in terms of a language core of essential constructs; the convenient, higher-level features could be "desugared" and decomposed into that subset.[3] This is, in fact, the usual mathematical practice of building up from primitives.

Building on Landin's distinction between essential language constructs and syntactic sugar, in 1991, Matthias Felleisen proposed a codification of "expressive power" to align with "widely held beliefs" in the literature. He defined "more expressive" to mean that without the language constructs in question, a program would have to be completely reorganized.[4]

Notable examples

  • In COBOL, many of the intermediate keywords are syntactic sugar that may optionally be omitted. For example, the sentence MOVE A B. and the sentence MOVE A TO B. perform exactly the same function, but the second makes the action to be performed clearer.
  • Augmented assignment or compound assignment operators: For example, a += b is equivalent to a = a + b in C and similar languages, assuming a has no side effects such as if a is a regular variable.[5][6] Some languages, such as Python[7] may allow overloading augmented assignment operators, so they may behave differently than standard ones.
  • In Perl, unless (condition) {...} is syntactic sugar for if (not condition) {...}. Additionally, any statement can be followed by a condition, so statement if condition is equivalent to if (condition) {statement}, but the former is more naturally formatted on a single line.
  • In the C language, the a[i] notation is syntactic sugar for *(a + i).[8] Likewise, the a->x notation is syntactic sugar for accessing members using the dereference operator (*a).x.
  • The using statement in C# ensures that certain objects are disposed of correctly. The compiler expands the statement into a try-finally block.[9]
  • The C# language allows variables to be declared as var x = expr, which allows the compiler to infer the type of x from the expression expr, instead of requiring an explicit type declaration. Similarly, C++ allows auto x = expr since C++11 and Java allows var x = expr since Java 11.
  • Python list comprehensions (such as [x*x for x in range(10)] for a list of squares) and decorators (such as @staticmethod).
  • In Haskell, a string, denoted in quotation marks, is semantically equivalent to a list of characters. An optional language extension OverloadedStrings allows string literals to produce other types of values, such as Text, as well.
  • In the tidyverse collection of R packages, the pipe, denoted by %>%, declares that the data (or output of the function) preceding the pipe will serve as the first argument for the function following the pipe.[10] So, x %>% f(y) is equivalent to f(x,y).
  • In SQL, a mere JOIN is equivalent to an INNER JOIN, the latter clarifying that the join statement is specifically an inner join operation as opposed to an outer join operation. Likewise, one may omit the OUTER from the LEFT OUTER JOIN, RIGHT OUTER JOIN and FULL OUTER JOIN.
  • Extension method in OOP languages in the form of myObject.myMethod(parameter1, parameter2, parameter3) is syntactic sugar for calling a global function as myMethod(myObject, parameter1, parameter2, parameter3). The reference to the object is passed as a hidden argument, usually accessible from within the method as this.
  • A parameter called by reference is syntactic sugar for technically passing a pointer as the parameter, but syntactically handling it as the variable itself, to avoid constant pointer de-referencing in the code inside the function.
  • In Java, an import declaration enables the compiler to find classes that are not otherwise specified with fully qualified names. For example import javax.swing.*; allows the programmer to reference a Swing object such as javax.swing.JButton using the shorter name JButton.
  • In the ES6 version of JavaScript, arrow functions have a short form (x) => x + 1, which is equivalent to the longer form (x) => { return x + 1; }.
  • In Scala, triple questions marks ( ??? ) is equivalent to throw new NotImplementedError . This is useful to mark a place for code that has not yet been written.[11]

Criticism

Some programmers feel that these syntax usability features are either unimportant or outright frivolous. Notably, special syntactic forms make a language less uniform and its specification more complex, and may cause problems as programs become large and complex. This view is particularly widespread in the Lisp community, as Lisp has very simple and regular syntax, and the surface syntax can easily be modified.[12] For example, Alan Perlis once quipped in "Epigrams on Programming", in a reference to bracket-delimited languages, that "Syntactic sugar causes cancer of the semi-colons".[13]

Derivative terms

Syntactic salt

The metaphor has been extended by coining the term syntactic salt, which indicates a feature designed to make it harder to write bad code.[14] Specifically, syntactic salt is a hoop that programmers must jump through just to prove that they know what is going on, rather than to express a program action.

In C#, when hiding an inherited class member, a compiler warning is issued unless the new keyword is used to specify that the hiding is intentional.[15] To avoid potential bugs owing to the similarity of the switch statement syntax with that of C or C++, C# requires a break for each non-empty case label of a switch (unless goto, return, or throw is used) even though it does not allow implicit fall-through.[16] (Using goto and specifying the subsequent label produces a C/C++-like fall-through.)

Syntactic salt may defeat its purpose by making the code unreadable and thus worsen its quality – in extreme cases, the essential part of the code may be shorter than the overhead introduced to satisfy language requirements.

An alternative to syntactic salt is generating compiler warnings when there is high probability that the code is a result of a mistake – a practice common in modern C/C++ compilers.

Syntactic saccharin

Other extensions are syntactic saccharin and syntactic syrup, meaning gratuitous syntax that does not make programming any easier.[17][18][19][20]

Sugared types

Data types with core syntactic support are said to be "sugared types".[21][22][23] Common examples include quote-delimited strings, curly braces for object and record types, and square brackets for arrays.

Notes

  1. ^ Landin, Peter J. (1964). "The mechanical evaluation of expressions" (PDF). The Computer Journal. 6 (4). Computer Journal: 308–320. doi:10.1093/comjnl/6.4.308. Retrieved 21 July 2014.
  2. ^ Abelson & Sussman 1996, Chapter 1, footnote 11.
  3. ^ Barbara Liskov, "A History of CLU", MIT Laboratory for Computer Science Technical Report 561 (1993)
  4. ^ Felleisen, Matthias (December 1991). "On the Expressive Power of Programming Languages". Science of Computer Programming. 17 (1–3). Springer-Verlag: 35–75. doi:10.1016/0167-6423(91)90036-W. Retrieved 19 July 2014.
  5. ^ "C Compound Assignment". msdn.microsoft.com. Microsoft. Retrieved 20 June 2016. However, the compound-assignment expression is not equivalent to the expanded version because the compound-assignment expression evaluates expression1 only once, while the expanded version evaluates expression1 twice: in the addition operation and in the assignment operation.
  6. ^ Garavaglia, Emilio (26 July 2015). "Why are shortcuts like x += y considered good practice?". stackexchange.com. Retrieved 20 June 2016. optimization can [be done] if 'finding x' has no side effects
  7. ^ "Python Data model". docs.python.org. 21 December 2020.
  8. ^ Raymond, Eric S. (11 October 1996). The New Hacker's Dictionary – 3rd Edition. MIT Press. p. 432. ISBN 978-0-262-68092-9. Retrieved 5 August 2012.
  9. ^ "using Statement (C# Reference)". Retrieved 16 September 2014.
  10. ^ "magrittr: Vignette". Retrieved 24 December 2018.
  11. ^ "Stack Overflow: What does the triple question mark mean in scala?". Retrieved 23 January 2024.
  12. ^ Abelson & Sussman 1996, Chapter 1, footnote 11.
  13. ^ Perlis 1982, Epigram #3.
  14. ^ "The Jargon File - syntactic salt". 2003-06-12. Archived from the original on 2003-06-12. Retrieved 2018-03-19.
  15. ^ "new Modifier (C# Reference)". microsoft.com. Microsoft. Retrieved 3 August 2015.
  16. ^ "switch (C# Reference)". microsoft.com. Microsoft. Retrieved 3 August 2015.
  17. ^ "syntactic sugar". catb.org. Retrieved 3 August 2015.
  18. ^ Boiten, Eerke A.; Möller, Bernhard (2002-06-26). Mathematics of Program Construction. Springer. ISBN 9783540438571. Retrieved 3 August 2015.
  19. ^ Dean, Thomas (2004). Talking with Computers: Explorations in the Science and Technology of Computing. Cambridge University Press. p. 115. ISBN 9780521542043.
  20. ^ Harrison, William; Sheard, Tim (July 8–10, 2002). "Mathematics of Program Construction" (PDF). Mathematics of Program Construction: 6th International Conference, MPC 2002, Dagstuhl Castle, Germany, July 8–10, 2002. Proceedings. International Conference on Mathematics of Program Construction. Lecture Notes in Computer Science. Vol. 2386. Dagstuhl Castle, Germany: Springer Berlin Heidelberg. p. 93. doi:10.1007/3-540-45442-X_6. ISBN 978-3-540-43857-1. S2CID 10059915. Archived from the original (PDF) on March 31, 2017.
  21. ^ Chugh, Ravi (2013). Nested Refinement Types for JavaScript (PhD). UC San Diego.
  22. ^ "C Language LLVM Documentation". clang.llvm.org. Retrieved 30 June 2020.
  23. ^ "The Secret Life of Types in Swift". medium.com/@slavapestov. 14 July 2016. Retrieved 30 June 2020.

References

Read other articles:

Artikel ini tidak memiliki referensi atau sumber tepercaya sehingga isinya tidak bisa dipastikan. Tolong bantu perbaiki artikel ini dengan menambahkan referensi yang layak. Tulisan tanpa sumber dapat dipertanyakan dan dihapus sewaktu-waktu.Cari sumber: Trisara FM – berita · surat kabar · buku · cendekiawan · JSTOR Trisara FM (PM3FRO)Wilayah siarCianjur dan sekitarnyaSloganJelas beda, beda jelasFrekuensi93.9 FMFormatHot AC Top 40, Easy Listening, Classi...

Rizki Syarif adalah seorang gitaris dan fisikawan partikel asal Indonesia. Namanya pertama kali dikenal sebagai gitaris grup musik Alexa.[1] Namun, pada tahun 2011, ia memutuskan untuk keluar dari grup tersebut untuk menempuh pendidikan S2 di bidang fisika di Universitas Sydney, Australia.[2] Setelah itu, ia melanjutkan pendidikannya ke jenjang S3 di Universitas Brown.[3] Fokus penelitiannya adalah pencarian partikel-partikel eksotik dengan perhatian khusus pada partik...

Akebi's Sailor UniformSampul dari volume manga pertama明日ちゃんのセーラー服(Akebi-chan no Sērāfuku) MangaPengarangHiroPenerbitShueishaImprintYoung Jump ComicsMajalahTonari no Young JumpDemografiSeinenTerbit2 Agustus, 2016 – sekarangVolume12 Seri animeSutradaraMiyuki KurokiSkenarioRino YamazakiMusikKana UtataneStudioCloverWorksPelisensiFunimation SEA Muse Communication[1][2]SaluranasliTokyo MX, GTV, GYT, BS11, MBS, BS AsahiTayang 9 Januari, 2022 – 27 Maret, 20...

vteWar in Iraq (2013–2017)Battles and operations 1st Anbar 1st Fallujah 1st Northern Iraq 1st Mosul Badush prison Camp Speicher 1st Kirkuk 2nd Northern Iraq Zumar 1st Sinjar Mosul Dam Musab bin Umair mosque Suq al-Ghazi Saqlawiyah 1st Hīt Jurf al-Sakhar Salahuddin 1st Baiji Siege of Amirli 1st Tikrit 2nd Baiji 3rd Baiji Dhuluiya 2nd Tikrit 1st Ramadi 2nd Sinjar 2nd Mosul 2nd Kirkuk Al-Karmah 2nd Anbar 2nd Ramadi 2nd Fallujah 2nd Hīt Ar-Rutbah 3rd Fallujah 3rd Sinjar Nineveh Plains offensi...

Loddon Shire Local Government Area van Australië Locatie van Loddon Shire in Victoria Situering Staat Victoria Hoofdplaats Wedderburn Coördinaten 36°25'6ZB, 143°52'0OL Algemene informatie Oppervlakte 6.700 km² Inwoners 8.351 (juni 2006) Overig Wards 4 Portaal    Australië Loddon Shire is een Local Government Area (LGA) in Australië in de staat Victoria. Loddon Shire telt 8.351 inwoners. De hoofdplaats is Wedderburn.

秋田県立大曲農業高等学校 北緯39度26分59秒 東経140度28分30秒 / 北緯39.44972度 東経140.47500度 / 39.44972; 140.47500座標: 北緯39度26分59秒 東経140度28分30秒 / 北緯39.44972度 東経140.47500度 / 39.44972; 140.47500過去の名称 秋田県尋常中学校農業専修科秋田県簡易農学校秋田県農業学校秋田県立秋田農業学校秋田県立大曲農業学校国公私立の別 公立学校設...

Image of spiral galaxy M81 combining data from the Hubble, Spitzer, and GALEX space telescopes. Density wave theory or the Lin–Shu density wave theory is a theory proposed by C.C. Lin and Frank Shu in the mid-1960s to explain the spiral arm structure of spiral galaxies.[1][2] The Lin–Shu theory introduces the idea of long-lived quasistatic spiral structure (QSSS hypothesis).[1] In this hypothesis, the spiral pattern rotates with a particular angular frequency (patt...

قرية قعوان  - قرية -  تقسيم إداري البلد  اليمن المحافظة محافظة المحويت المديرية مديرية ملحان العزلة عزلة العسوس السكان التعداد السكاني 2004 السكان 273   • الذكور 131   • الإناث 142   • عدد الأسر 25   • عدد المساكن 23 معلومات أخرى التوقيت توقيت اليمن (+3 غرينيتش) �...

Central Violations BureauLogoAgency overviewJurisdictionUnited StatesHeadquartersP.O. Box 780549 San Antonio, TX 78278Parent agencyAdministrative Office of the U.S. CourtsWebsitehttps://www.cvb.uscourts.gov/index.html The Central Violations Bureau (CVB) is a national center in the United States responsible for processing violation notices (tickets) issued and payments received for petty offenses charged on a federal violation notice. This includes violations that occur on federal property suc...

Former urban farm in Los Angeles This article has an unclear citation style. The references used may be made clearer with a different or consistent style of citation and footnoting. (January 2023) (Learn how and when to remove this template message) A banner on the fence surrounding the former grounds of the South Central Farm The son of a farmer holding seeds Crops at South Central Farm Kitchen at the farm The South Central Farm, also known as the South Central Community Garden, was an urban...

Ten artykuł dotyczy Planu operacyjnego „Wschód”. Zobacz też: inne plany wojskowe oznaczone kryptonimem „W”. Plan operacyjny „Wschód” – plan operacyjny Wojska Polskiego II RP na wypadek wojny ze Związkiem Radzieckim. Plan wojny obronnej ze wschodnim sąsiadem, w odróżnieniu od planu „Zachód” był opracowywany przez cały okres II RP. Plan „Wschód” nie zachował się jednak w formie jednolitego dokumentu, nieznane są też jego dokładne założenia. Do jego oprac...

حسن عبد الرسول معلومات شخصية اسم الولادة حسن عبد الرسول حسن دشتي تاريخ الميلاد 1951 الوفاة 25 ديسمبر 2016 (بعمر 65)الكويت الجنسية  الكويت الحياة العملية المهنة ممثل  سنوات النشاط 1974 - 2012 المواقع السينما.كوم صفحته على موقع السينما تعديل مصدري - تعديل   حسن عبد الرسول (1951 - 25 د�...

Tristan HoareTypeContemporary art galleryFounded2009FounderTristan HoareWebsitewww.tristanhoare.co.uk Tristan Hoare is an art dealer and contemporary art gallery in London that focusses on emerging and established artists. History The gallery was established in 2009 by Tristan Hoare. Between 2009 and 2013, it was located at Lichfield Studios, the former studio of British photographer Patrick Lichfield between 1984 and 2005.[1][2] The gallery's new premises at 6 Fitzroy Square ...

Pentecostal Christian denomination in India General Council of the Assemblies of God of IndiaLogoClassificationEvangelical ChristianityTheologyPentecostalSuperintendentRev. Paul ThangiahAssociationsWorld Assemblies of God FellowshipHeadquartersChennai, IndiaOrigin1995Congregations5,200Official websiteassembliesofgod.in The General Council of the Assemblies of God of India is a Pentecostal Christian denomination in India. It is affiliated with the World Assemblies of God Fellowship. The headqu...

{{{Header}}} Singkatan: {{{Abbreviation}}} (pinyin: {{{AbbrevPinyin}}}) [[Berkas:{{{Map}}}|{{{MapSize}}}|{{{Name}}} ditandai di peta ini]] Asal nama 河 hé - Sungai Batang(Kuning) 北 běi - utara utara dari Sungai Kuning Tipe administrasi Provinsi Ibu kota Muara Shijiazhuang Kota terbesar Muara Hebei Sekretaris PKT Wang Dongfeng [1] Gubernur Xu Qin [2] Wilayah 298.700 km² (ke-12) Populasi (Tahun)  - Kepadatan 67.690.000 (ke-6) 361/km² (ke-11) PDB (2003) - per kapita CNY ...

Beauty pageant edition Miss World 1962Catharina Lodders, Miss World 1962Date8 November 1962PresentersMichael AspelVenueLyceum Ballroom, London, United KingdomBroadcasterBBCEntrants33Placements15WithdrawalsBoliviaCeylonLebanonMadagascarNicaraguaRhodesia and NyasalandSurinameTurkeyReturnsCanadaJamaicaJordanPortugalWinnerCatharina Lodders Holland← 19611963 → Miss World 1962 was the 12th edition of the Miss World pageant, held on 8 November 1962 at the Lyceum Ballroom i...

39°45′45.50″N 105°0′42.88″W / 39.7626389°N 105.0119111°W / 39.7626389; -105.0119111 Highlands sometimes refers to two distinct but adjacent Denver neighborhoods that are highlighted in this map of Denver's official neighborhoods. Highland is a distinct city-center neighborhood in Denver, Colorado, United States, bounded by West 38th Avenue to the north, a Union Pacific Railroad line on the east, the South Platte River to the southeast, Speer Boulevard on th...

Gas

Disambiguazione – Se stai cercando altri significati, vedi Gas (disambigua). Rappresentazione di un sistema gassoso secondo la teoria cinetica dei gas Un gas è un aeriforme la cui temperatura è superiore alla temperatura critica; di conseguenza, i gas non possono essere liquefatti senza prima essere raffreddati, al contrario dei vapori. Un gas è un fluido che non ha volume proprio (tende a occupare tutto il volume a sua disposizione) e che è facilmente comprimibile.[1] Nell'uso...

דיאגרמה המראה מסלולים סביב כדור הארץ, המסלול הנמוך מסומן בתכלת. המסלול של תחנת החלל הבינלאומית מסומן בקו האדום שבתוך התכלת, מסלול לווייני בינוני מסומן בצהוב ומסלול גאוסטציונרי בקו השחור. מסלול לווייני נמוך (באנגלית: LEO - Low Earth Orbit) הוא מסלול סביב כדור הארץ בגובה של עד 2,000 קילו�...

السوسي معلومات شخصية الحياة العملية المهنة عالم دراسات إسلامية،  وقارئ القرآن  تعديل مصدري - تعديل   يوجد في ويكي مصدر كتب أو مستندات أصيلة عن النص الكامل للقرآن الكريم برواية السوسي لقراءة أبي عمرو بن العلاء السوسي أحد قراء القران الكريم، اسمه أبو شعيب صالح بن زيا�...