Talk:Syntactic sugar

Page contents not supported in other languages.
From Wikipedia, the free encyclopedia

Syntactic aspartame[edit]

The term ¨Syntactic aspartame¨ has been thrown around lately whilst discussing pugs. Anyone care to enlarge the current article? elpincha 19:30, 27 February 2006 (UTC)[reply]

Suggest we merge 'Syntactic saccharin' and 'Syntactic Splenda' sections into one, and include this variant in the text. Twifkak 02:49, 10 December 2006 (UTC)[reply]

rewrite needed[edit]

The last paragraph (Splenda) needs rewriting.

Mediawiki example[edit]

I removed this:

"A Mediawiki example would be the ability of signing one's comments in talk pages with --~~~~. The users could manually insert the Wiki code that this is short for, but the syntactic sugar makes it easier."

It's hard to argue that "~~~~" is sugar; it's more like a macro. Especially for the default expansion, it is not simply the case that users could manually insert the "equivalent" code, because this requires them to know their IP address (at least for anonymous users) and the time at the Mediawiki servers in UTC. It's comparable to macros like __LINE__ in C, expanding to the current line number: you could conceivably go through the trouble of finding the expansion out yourself, but that doesn't make the construct syntactic sugar.

As an aside, how notable are the "syntactic foo" variants people have come up with? "Syntactic sugar" and "syntactic salt" are in common use, but the others look like obscure, one-off expressions to me. Not every clever variation people think of should make it into an encyclopedia. 194.151.6.70 22:20, 25 November 2006 (UTC)[reply]

Variants[edit]

As an aside, how notable are the "syntactic foo" variants people have come up with? "Syntactic sugar" and "syntactic salt" are in common use, but the others look like obscure, one-off expressions to me. Not every clever variation people think of should make it into an encyclopedia.

I agree with this. A DHH blog post is not a reasonable source for an encyclopedia. I've removed that one, others are welcome to put it back or remove others they know to be 'one off' terms. 24.52.132.106 22:45, 5 December 2006 (UTC)[reply]

I also agree. I have never heard of "Syntactic saccharin" and the definition provided does not seem to follow the same analogy as saccharin adds sweetness without adding (many) calories. In that sense it would follow that "Syntactic saccharin" provides the benefits of "Syntactic sugar" with less added syntax. The definition provided suggests that it instead provides no additional sweetness but still adds mass, making it more like an inert "Syntactic salt". But regardless of the definition we give, the term does not appear to be in wide circulation. 216.36.186.2 (talk) 16:00, 7 January 2008 (UTC)[reply]

I've been programming for 25 years and never heard or saw the term syntactic salt. It's a very useful term, but I too propose to strike it. Rp (talk) 08:39, 2 October 2009 (UTC)[reply]

Explanation Needed[edit]

However many modern, "sugar-rich" languages (such as C#) cannot be desugared. Still, their features may be considered "sugar" because primitives exist in predecessor languages (such as C) to fully recreate them.

One would be lead to believe that if a predecessor language can fully recreate the features in a derivative, then this is in fact the definition of syntactic sugar. This needs to be cited, or the fact C is not a subset of C# needs to be explained. —Preceding unsigned comment added by 142.151.168.69 (talk) 04:33, 8 February 2008 (UTC)[reply]

Technically, any construct beyond if and goto could be described as "syntactic sugar". I do think that sentence is rather pointless. I mean, anything you can do in C# can also be done in assembler - doesn't mean you'd particularly want to! DeanHarding (talk) 06:29, 4 July 2008 (UTC)[reply]
I have removed it. Similarly, it goes a bit far to consider C++ a bunch of syntactic sugar for C, even though C++ was originally implemented as a preprocessor for C. Rp (talk) 12:54, 3 April 2009 (UTC)[reply]

Basic definition[edit]

I believe that the basic definition the article starts with -- "Syntactic sugar is a term coined by Peter J. Landin for additions to the syntax of a computer language that do not affect its functionality but make it "sweeter" for humans to use." -- is incorrect. It implies that syntactic sugar is an "addition" to an existing programming language and that therefore syntactic sugar can be "translated back" into the language. That was not Landin's point at all. Most languages (certainly when he was writing) did not support anonymous functions (lambda expressions), for example. --Macrakis (talk) 00:27, 5 July 2008 (UTC)[reply]

You're right: Landin apparently said that ALGOL 60 is lambda calculus plus syntactic sugar. S he was using the term in a different sense. I'm not sure how widespread that sense is today. Rp (talk) 13:03, 3 April 2009 (UTC)[reply]

"Alternative Terms"???[edit]

The phrase "Alternative Terms" makes me think of synonyms. Maybe renaming it to "Related Terms" or "Similar Terms," or something? Txmy (talk) 19:24, 7 December 2008 (UTC)[reply]

I strongly disagree[edit]

Sorry, I think that this article examples go to far in what they consider to be "syntactic sugar". IMO if ___exactly the same___ can be obtained with a slightly more complicated construct, then it's syntactic sugar. One example is Pascal's "with" keyword:

  with something {
   a = 3;
   myfunction(x);
  }

is

  something.a = 3;
  something.myfunction(x);

with some sugar.


But I don't think C-style for loop is not syntactic sugar.


for(A;B;C) body ;

might look the same as:

A; while(B) { body ; C ; }

but the for() variant adds some functionality. If you "continue" from inside the body, the code in "C" still gets evaluated. Replicating this behavior on the while() might require the use of flag variables, or duplicating the code for C.

Then it goes with replacing while() with goto's. I just think that this is going too far, and using the same arguments you can argue that the whole C language is syntactic sugar over assembler, then assembler is syntactic sugar for machine code (hey, I can buy that one), and then machine code is just syntactic sugar over placing the 1 and 0 directly into the memory. 84.77.96.100 (talk) 16:34, 17 July 2009 (UTC)[reply]

The problem is that the original and present-day meaning of the terms do not appear to coincide - so it's not clear how different speakers use the term exactly. Rp (talk) 08:41, 2 October 2009 (UTC)[reply]
I'd say that the same counts for all examples, especially for the example of Object oriented programming in C. It's way far fetched to call C++ syntactic sugar for C, or C# syntactic sugar for C++, neiter is C syntactic sugar for assembly, assembly for the actual processor opcodes, etc. The string literals example is rather vague. The array access might be considered as an example where it could have been used for, but I would rather keep to the original use as described in the first alinea, possible mentioning of other examples where others have named it like that, but then refer to the actual persons who have used it like that, instead of making up artificial examples. anoko_moonlight (talk) 21:43, 24 April 2011 (UTC)[reply]
C# properties are also not just 'syntactic sugar'. You need to understand why properties exist to see this is the case. See Uniform Access Principle article for a description of the problem properties solve that isn't solved by just having the 'getter' and 'setter' methods without the syntax. --Aflafla1 (talk) 20:45, 14 February 2012 (UTC)[reply]

C multidimensional array example[edit]

The existing example states that the address of the memory cell containing a[i][j] is *(*(a + i) + j), rather than *(a + i * columns-per-row + j). The former would perhaps be more appropriate for (a[i])[j]. Any objections to my replacing this strange construct with the one for the more common double dimensional array? Traumerei (talk) 04:20, 17 February 2010 (UTC)[reply]

I agree with Traumerei.*(a+i) is itself syntactic sugar for

  • ((unsigned int)a + i* sizeof(element_of_a)). in this case sizeof(element_of_a)is columns-per-row as a is an array of arrays of size columns-per-row.

shall i go ahead and and make the corrections he suggested? R6im3t (talk) 08:06, 9 May 2010 (UTC)[reply]

For the primitive array type, a[i][j] is not equivalent to *(*(a + i) + j), since the array is the single indirection as described by Traumerei, while the double indirection will treat the element at (a + i) as a pointer.Consider the following code snippet 'a[2][2] = { { 0, 0 }, {0 , 0} }; *(*(a + 1) + 0) = 1; // should be a[1][0] = 1': if executed as describe will dereference 0 (NULL pointer) since *(a + 1) = 0. 2-dimensional arrays in C/C++ are not arrays of arrays: a primitive array type is just a pointer in C/C++ regardless of dimension. The syntax is a convenient way to specify some ranking of elements from the base address. A lot of C++ texts seem to have this kind of error since objects that mimic the array syntax may actually use double indirection logic and syntax such as 'a[2][2]; int * ptr = a[1];' are allowed (which means that 'ptr = (a + 1)', which is still correct since 'a' is a pointer). I think the article could benefit from explicitly pointing out this type of obfuscation: things look like they are doing one thing but are really doing something else due to a perceived need to make the syntax uniform (appealing/sweet). It as an example showing the perils of syntactic sugar or at least bad abstraction in my opinion (it would be easier to think that each [] is an indirection but for primitive C/C++ arrays it isn't). 173.206.27.201 (talk) 13:50, 22 May 2010 (UTC)[reply]

Of course it is because C/C++ arrays are equal to their addresses. (a+i) has result of type int(*)[2] (it is pointer to a[i]) and dereferencing it results in int[2] (a[i] itself, which will be converted int* - pointer to a[i][0] as necessary). Following code will display the same address 3 times: int a[2][2]; cout << &a << endl; cout << a << endl; cout << *a << endl; Dereferencing pointer to array does no indirection, it simply changes type. Drundia (talk) 16:38, 23 April 2013 (UTC)[reply]

Examples ?[edit]

There is now absolutely no concrete examples of syntactic sugar on this page apart from those two rather vague sentence in the beginning (and the case of the for loop in C is far from cut and dried, as other commentators remarked). The section on Derivative terms (which I never heard anywhere before whereas syntactic sugar is often used) is actually far bigger than the examples. I note that examples were removed in the past. Is it fine to add some properly referenced and illustrated examples once again ? For instance, Haskell is a language that has several examples of syntactic sugar that are clearly labeled as such and translated back to primitives in the Haskell Report. The string literal example was badly presented but is very much true in at least two senses : interpolation, and case like Haskell where strings are simply list of characters with a special syntax. Jedai (talk) 19:57, 20 January 2012 (UTC)[reply]

I think the root of the problem is the lack of clear, sourced definitions of the term. If we're not sure what we're talking about, examples become difficult to agree on. Rp (talk) 19:01, 21 January 2012 (UTC)[reply]

I'm not an expert so please correct me if I'm wrong; I think Perl's use of => as an exact synonym for a comma (most often used in declarations of hash literals) is an uncontentious example. AFAICT, it exists purely to make code easier to read and has no other semantic effects. 80.176.190.231 (talk) 18:30, 18 February 2012 (UTC)[reply]

Okay guys, someone who knows about this stuff needs to add an example to the lead section. If nobody else does, I'm going to do my inept best to add one myself InternetMeme (talk) 21:04, 4 August 2012 (UTC)[reply]

Concrete C# Examples[edit]

I'm not fully happy with the "Augmented Assignment" example. In C#[1], for example, the form "a += b" is not equivalent to "a = a + b", even though it usually produces the same results. Here's an example, in C#, of its not producing the same result:

   int TimesRead;  //This is set to 1 when b is fetched
   int b {
     get {
       int a = TimesRead;
       TimesRead = 1;
       return a;
     }
   }  // end: b
   public void WikiSugarDemo() {
     int[] a;
     a = new[] { 3, 10 };
     TimesRead = 0;
     a[b] = a[b] + 2;
     Console.WriteLine(
             "Using a[b] = a[b] + 2:\t"
             + "a[0]=" + a[0]
             + "; a[1]=" + a[1]
           );
     a = new[] { 3, 10 };
     TimesRead = 0;
     a[b] += 2;
     Console.WriteLine(
             "Using a[b] += 2:\t"
             + "a[0]=" + a[0]
             + "; a[1]=" + a[1]
           );
     //Generated output:
     //
     //Using a[b] = a[b] + 2:  a[0]=12; a[1]=10
     //Using a[b] += 2:        a[0]=5; a[1]=10
   }  // end: WikiSugarDemo()

I think that a suitable example of "syntactic sugar" might be the C# "var" keyword (called an "implicitly typed local variable declaration"), which may sometimes be used to substitute for an explicit type specification. The sugary part of "var" is that it avoids repeating a lengthy type name; e.g., the statement

     System.Collections.Generic.List<string> d =
           new System.Collections.Generic.List<string>();

may be shortened to

     var d = new System.Collections.Generic.List<string>();

(Use of "var" is sometimes necessary, as when the expression is of an anonymous type.)

--PoisonCat1 (talk) 08:41, 17 March 2014 (UTC)[reply]

References

  1. ^ "C# Language Specification". Microsoft. Retrieved 17 March 2014.

Potential C++ Example[edit]

Does operator overloading count as syntactic sugar? It feels like it to me, but I don't believe I'm experienced enough to fully trust my opinion on this.

     class Integer {
         int val;
       public:
         Integer(int i) : val(i) {}
         operator int() { return val; }
         Integer& operator+=(const Integer& other) {
             val += other.val;
             return *this;
         }
     };
     Integer operator+(const Integer& l, const Integer& r) {
         Integer ret = l;
         ret += r;
         return ret;
     }

In this case, operator+() serves as syntactic sugar for creating a new Integer equivalent to the sum of two other Integers.

     Integer i = 5, j = 10;
     Integer k = i + j;
     /* Equivalent to...
      *
      *     Integer k = operator+(i, j);
      *
      * Which is itself sugar for...
      *
      *     Integer k = i; k += j;
      *
      * Which is ITSELF sugar for accessing and modifying k's field
      * "val" directly.
      */

Not 100% sure if this counts.

Alternatively, the C++11 type deduction rules can be seen as syntactic sugar (albeit extremely valuable sugar), which can be used similarly to var in the above C# example.

     // Old:
     std::vector<int>::iterator it = vec.begin();
     // C++11:
     auto it = vec.begin();

This is both sugar, and extremely useful in contexts where the actual type isn't necessarily known to the programmer; it uses template type deduction rules, so the type can be determined for you by the compiler in most cases.

The article on Operator overloading claims it is (and even wikilinks back to this article) and cites the C++ FAQ lite [1] Michaelmalak (talk) 15:47, 10 January 2017 (UTC)[reply]

--173.237.102.207 (talk) 04:43, 8 January 2017 (UTC)[reply]

Java example[edit]

Are the inner classes in Java and from there the lambdas in Java 8 a good extended example of syntactic sugar?

When you write:

   button.addActionListener((e)->System.out.println("Hello world"));

this is the short form of:

   button.addActionListener(new ActionListener() {
       @Override
       public void actionPerformed(ActionEvent e) {
            System.out.prinln("Hello world");
       }
   });

and even this still gets some major changes at compile time because inner classes are like normal classes but with a special link to the outer class. Piegames (talk) 13:11, 7 June 2017 (UTC)[reply]

Excellent question. IMO, this applies to even C from the 1980s because C had function pointers. But function pointers are not functional programming. IMO, we need a new section not on Java 8, but on "anonymous functions declared inline as a weak imitation of functional programming". With citations, of course. Here is one https://people.cs.umass.edu/~yannis/fc++/fc++.main.pdf

Auto-type declarations[edit]

In C++, C# and D, auto-type declarations can be used to declare a variable whose type is not known at coding time when doing generic programming. In this respect, it is arguably a feature that adds power to the languages in question, thus not syntactic sugar.

That said, you could argue that auto x = expr; is syntactic sugar for typeof(expr) x = expr; in D, or decltype(expr) x = expr; in C++11. But I'm not sure that the same can be said about C# or Java. — Smjg (talk) 23:17, 30 August 2022 (UTC)[reply]

Poor OOP Example[edit]

I think the given example for syntactic sugar in OOP languages isn't very good, as it's underselling what's going on within OOP under the hood.

  • Method calling 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.

This is true in the specific case of final methods, or in more recent languages like Kotlin, static extension methods. However, this does not apply to typical object methods. For example, in Java, myList.get(index) cannot be replaced with some global List.get(myList, index). At runtime, when get is called, the runtime does a dynamic dispatch to the get method specific to the class of myList, uniquely tailored to that particular class and able to access its private fields.

There is no way to recapture the full functionality and expressive power of this dynamic dispatch with the rest of Java's feature, so it cannot be considered syntactic sugar.

I think a better example for OOP would be the for-each loop, which on arrays is syntactic sugar for a for-loop for each index in the array, and on Iterables is syntactic sugar for a while-loop using its Iterator. This still demonstrates a unique advantage of OOP with the Iterable interface, but is true syntactic sugar. Derektom14 (talk) 07:22, 17 June 2023 (UTC)[reply]

COBOL noise words[edit]

The cobol

 move a to b

goes beyond syntactic sugar, in that the 'in' can be removed without any other change, and the line remains valid and does the same thing (whereas doing C strings without quotes requires some work). Back in the day, these were sometimes called noise words. There were various programs that could take COBOL source and add (or remove) all the noise words, which was handy when your manager used "amount of code written" as a metric. 203.13.3.89 (talk) 04:28, 11 April 2024 (UTC)[reply]