Syntactic sugar

From HaskellWiki
Revision as of 01:44, 27 October 2017 by Matrixmike (talk | contribs) (spelling vs meaning)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Syntactic Sugar is the name for special notations for special applications. They don't add functionality to a language, they are plain textual replacements for expressions that could also be written in a more analytic way.

Haskell employs a lot of syntactic sugar. For example x `elem` xs is sugar for elem x xs, `elem` xs is sugar for flip elem xs, [1,2,3] is sugar for (1:2:3:[]) and do x <- f; g x is sugar for f >>= (\x -> g x).

There are lots of /Pros and /Cons to syntactic sugar. The goal generally being to balance the amount of it available in a language so as to maximise readability -- giving enough freedom to allow the author to emphasize what is important, while being restrictive enough that readers will know what to expect.

A lot of discussion about the extent to which syntatic sugar should be used has been going on at ThingsToAvoid/Discussion, which seems to be rather a matter of taste. Thus the discussion at ThingsToAvoid/Discussion is being cut into two pages which state the pros and cons of syntactic sugar without intermediate discussion so as to make them easier to read. The reader may examine both positions and decide which points from each they like.


As a piece of meta-discussion, I don't think that the issue of syntactic sugar is as cut-and-dried as some people appear to be making it.

Too much syntactic sugar can make the underlying semantics unclear, but too little can obscure what is being expressed. The author of a piece of code chooses from the available syntax in order to emphasize the important aspects of what it does, and push the minor ones aside. Too much freedom in doing this can make code unreadable because there are many special cases in the syntax for expressing peculiar things which the reader must be familiar with. Too little freedom can also result in unreadability because the author has no way to emphasize any particular way of thinking about the code, even though there may be many ways to look at it when someone new to the code starts reading. It can also make it harder to write code, because there are fewer ways to express any given idea, so it can be more difficult to find one which suits you. One can argue that this is a task for comments to perform, but when it comes time to read the code, it is really the code itself that is readable or not.

As for my own opinion on the matter, I think that Haskell has so far done a very good job in balancing the amount of syntactic sugar so as to be flexible enough allow the author to be clear and concise, but firm enough to be comprehensible to new eyes.

- CaleGibbard