Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Syntactic sugar

From Wikipedia, the free encyclopedia
Programming language syntax designed for ease of use
Code example of the short declaration syntactic sugar in the programming language Go

Incomputer science,syntactic sugar issyntax within aprogramming 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, in thePython programming language it is possible to get alist element at a givenindex using the syntaxlist_variable.__getitem__(index), but this is frequently shortened tolist_variable[index] which could be considered simpler and easier to read, despite having identical behavior. Similarly,list_variable.__setitem__(index, value) is frequently shortened tolist_variable[index] = 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 andexpressive power will remain the same.

Language processors, includingcompilers andstatic analyzers, often expand sugared constructs into their more verbose equivalents before processing, a process sometimes called "desugaring".

Origins

[edit]

The termsyntactic sugar was coined byPeter J. Landin in 1964 to describe the surface syntax of a simpleALGOL-like programming language which was defined semantically in terms of the applicative expressions oflambda calculus,[1][2] centered on lexically replacing λ with "where".

Later programming languages, such asCLU,ML andScheme, 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

[edit]
  • InCOBOL, many of the intermediate keywords are syntactic sugar that may optionally be omitted. For example, the sentenceMOVE A B. and the sentenceMOVE A TO B. perform exactly the same function, but the second makes the action to be performed clearer.
  • InPerl,unless(condition){...} is syntactic sugar forif(notcondition){...}. Additionally, any statement can be followed by a condition, sostatementifcondition is equivalent toif(condition){...}, but the former is more naturally formatted on a single line.
  • In theC language, thea[i] notation is syntactic sugar for*(a + i).[5] Likewise, thea->x notation is syntactic sugar foraccessing members using thedereference operator(*a).x.
  • Theusing statement inC# ensures that certain objects are disposed of correctly. The compiler expands the statement into atry-finally block.[6]
  • The C# language allows variables to be declared asvar x = expr, which allows the compiler toinfer the type ofx from the expressionexpr, instead of requiring an explicit type declaration. Similarly, C++ allowsauto x = expr since C++11 and Java allowsvar x = expr since Java 11.
  • Pythonlist comprehensions (such as[x*xforxinrange(10)] for a list of squares) anddecorators (such as@staticmethod).
  • InHaskell, a string, denoted in quotation marks, is semantically equivalent to a list of characters. An optional language extensionOverloadedStrings allows string literals to produce other types of values, such as Text, as well.
  • In thetidyverse collection ofR packages, thepipe, 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.[7] So,x %>% f(y) is equivalent tof(x,y).
  • InSQL, a mereJOIN is equivalent to anINNER 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 theOUTER from theLEFT OUTER JOIN,RIGHT OUTER JOIN andFULL OUTER JOIN.
  • Extension method in OOP languages in the form ofmyObject.myMethod(parameter1, parameter2, parameter3) is syntactic sugar for calling a global function asmyMethod(myObject, parameter1, parameter2, parameter3). The reference to the object is passed as a hidden argument, usually accessible from within the method asthis.
  • A parameter called by reference is syntactic sugar for technically passing apointer as the parameter, but syntactically handling it as the variable itself, to avoid constant pointer de-referencing in the code inside the function.
  • InJava, animport declaration enables the compiler to find classes that are not otherwise specified with fully qualified names. For exampleimport javax.swing.*; allows the programmer to reference aSwing object such asjavax.swing.JButton using the shorter nameJButton.
  • InJavaScript, if the key and value are the same in an object, you have the option to write it just once. For example,{name: name} is equivalent to{name}. This is called the Shorthand Property.
    • In theES6 version ofJavaScript, arrow functions have a short form(x) => x + 1, which is equivalent to the longer form(x)=>{returnx+1;}.
  • InScala, triple questions marks (???) is equivalent tothrownewNotImplementedError. This is useful to mark a place for code that has not yet been written.[8]

Criticism

[edit]

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 theLisp community, as Lisp has very simple and regular syntax, and the surface syntax can easily be modified.[9]For example,Alan Perlis once quipped in "Epigrams on Programming", in a reference tobracket-delimited languages, that "Syntactic sugar causes cancer of thesemi-colons".[10]

Derivative terms

[edit]

Syntactic salt

[edit]

The metaphor has been extended by coining the termsyntactic salt, which indicates a feature designed to make it harder to write bad code.[11] 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.

InC#, when hiding an inherited class member, a compiler warning is issued unless thenew keyword is used to specify that the hiding is intentional.[12] To avoid potential bugs owing to the similarity of theswitch statement syntax with that of C or C++, C# requires abreak for each non-emptycase label of aswitch (unlessgoto,return, orthrow is used) even though it does not allow implicitfall-through.[13] (Usinggoto and specifying the subsequent label produces a C/C++-likefall-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

[edit]

Other extensions aresyntacticsaccharin andsyntacticsyrup, meaning gratuitous syntax that does not make programming any easier.[14][15][16][17]

Sugared types

[edit]

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

Notes

[edit]
  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. Retrieved21 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. Retrieved19 July 2014.
  5. ^Raymond, Eric S. (11 October 1996).The New Hacker's Dictionary – 3rd Edition. MIT Press. p. 432.ISBN 978-0-262-68092-9. Retrieved5 August 2012.
  6. ^"using Statement (C# Reference)". Retrieved16 September 2014.
  7. ^"magrittr: Vignette". Retrieved24 December 2018.
  8. ^"Stack Overflow: What does the triple question mark mean in scala?". Retrieved23 January 2024.
  9. ^Abelson & Sussman 1996, Chapter 1,footnote 11.
  10. ^Perlis 1982, Epigram #3.
  11. ^"The Jargon File - syntactic salt". 2003-06-12. Archived fromthe original on 2003-06-12. Retrieved2018-03-19.
  12. ^"new Modifier (C# Reference)".microsoft.com. Microsoft. Retrieved3 August 2015.
  13. ^"switch (C# Reference)".microsoft.com. Microsoft. Retrieved3 August 2015.
  14. ^"syntactic sugar".catb.org. Retrieved3 August 2015.
  15. ^Boiten, Eerke A.; Möller, Bernhard (2002-06-26).Mathematics of Program Construction. Springer.ISBN 9783540438571. Retrieved3 August 2015.
  16. ^Dean, Thomas (2004).Talking with Computers: Explorations in the Science and Technology of Computing. Cambridge University Press. p. 115.ISBN 9780521542043.
  17. ^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 fromthe original(PDF) on March 31, 2017.
  18. ^Chugh, Ravi (2013).Nested Refinement Types for JavaScript (PhD). UC San Diego.
  19. ^"C Language LLVM Documentation".clang.llvm.org. Retrieved30 June 2020.
  20. ^"The Secret Life of Types in Swift".medium.com/@slavapestov. 14 July 2016. Retrieved30 June 2020.

References

[edit]
Retrieved from "https://en.wikipedia.org/w/index.php?title=Syntactic_sugar&oldid=1333889415"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2026 Movatter.jp