https://en.wikipedia.org/wiki/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.
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 like Array[i,j]
. Similarly an array element update is a procedure of three arguments, something like set_array(Array, vector(i,j), value)
, but many languages provide syntax like Array[i,j] = value
.
Specifically, a construct in a language is called 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, static analyzers, and the like, often expand sugared constructs into more fundamental constructs before processing, a process sometimes called "desugaring".
https://zh.wikipedia.org/wiki/语法糖
语法糖(Syntactic sugar),也译为糖衣语法,是由英国计算机科学家彼得·约翰·兰达(Peter J. Landin)发明的一个术语,指计算机语言中添加的某种语法,这种语法对语言的功能并没有影响,但是更方便程序员使用。通常来说使用语法糖能够增加程序的可读性,从而减少程序代码出错的机会。
语法糖的例子[编辑]
for循环[编辑]
一个例子是C语言中的for循环:
for (i = 0; i < 10; i++) { //P }
其效果和以下的while循环是一样的,其中P是循环要处理的主体。
i = 0; while (i < 10) { //P i++; }
中置表示法[编辑]
Haskell虽然是函数编程语言,但它提供了a + b这种“中置表示法”的语法,让程式更容易撰写,也比较容易阅读。
Lua[编辑]
在Lua中,一个变量的赋值方法如下:
foo = "bar"
而一个函数,作为基本类型之一,语法与定义变量的方法基本一致:
foo = function() print "bar" end
但是此种写法对于有其他编程语言背景的人来说不够直观,故Lua提供了如下的语法糖:
function foo() print "bar" end
它与上述方法效果完全一样,但是更加紧凑和易于理解。
衍生词语[编辑]
语法糖精(Syntactic saccharin)是由语法糖衍生的词语,是设计失败的语法糖,设计上无法方便程序员使用[1][2] 。
参见[编辑]
- 语法盐:和语法糖相反,有意使书写代码更加困难以避免人为疏失产生错误的语法
参考资料[编辑]
- ^ syntactic sugar. catb.org. [3 August 2015].
- ^ Mathematics of Program Construction. google.com. [3 August 2015].
分类: