Syntactic sugar
|
Syntactic sugar is a term coined by Peter J. Landin for additions to the syntax of a computer language that do not affect its expressiveness but make it "sweeter" for humans to use. Syntactic sugar gives the programmer (designer, in the case of specification computer languages) an alternative way of coding (specifying) that is more practical, either by being more succinct or more like some familiar notation. It does not affect the expressiveness of the formalism.
Syntactic sugar can be easily translated ("desugared") to produce a program (specification) in some simpler "core" syntax. In Landin's case, the core was a lambda calculus enriched with a few operations, such as assignment. Following Landin's insights, some later programming languages, such as ML and Scheme, were explicitly designed as a language core of essential constructs, into which other convenient features can be desugared. This is, in fact, the usual mathematical practice of starting from a minimal set of primitives, but doing most work in a convenient, special-purpose notation defined in terms of those primitives.
For instance, while it is common for most programming languages to include standard mathematical operations using infix notation (you will often find operations such as i + 1
throughout a typical program's source code) many of these languages (mainly those that are functional languages), handle the actual math by calling functions. In these cases the infix notation is actually syntactic sugar for something such as add(i, 1)
.
Another example is in the C programming language's handling of arrays. In C, arrays are constructed as blocks of memory, accessed via an offset from the array's starting point in memory. However, pointer math can often be "tricky" and error prone, so C provides the a[i]
syntax for what would otherwise be written as *(a + i)
Alan Perlis once quipped that "Syntactic sugar causes cancer of the semicolon."
The metaphor has been extended by coining the term syntactic salt, a feature designed to make it harder to write bad code. Specifically, syntactic salt is a hoop the programmer must jump through just to prove that he knows what's going on, rather than to express a program action. Some programmers consider required type declarations to be syntactic salt. A requirement to write "end if", "end while", "end do", etc. to terminate the last block controlled by a control construct (as opposed to just "end") is widely considered syntactic salt. Syntactic salt is like the real thing in that overuse tends to raise programmers' blood pressures in an unhealthy way.
The correct amout of both syntactic sugar and syntactic salt in a language is a matter of personal opinion, and thus is the subject of never-ending debate.
- This article was originally based on material from the Free On-line Dictionary of Computing, which is licensed under the GFDL.