语法糖(英语:Syntactic sugar)是由英国计算机科学家彼得·兰丁发明的一个术语,指计算机语言中添加的某种语法,这种语法对语言的功能没有影响,但是更方便程序员使用。语法糖让程序更加简洁,有更高的可读性。
举例来说,许多程序语言提供专门的语法来对数组中的元素进行引用和更新。从理论上来讲,一个数组元素的引用涉及到两个参数:数组和下标向量,比如这样的表达式:get_array(Array, vector(i, j))
。然而,许多语言支持这样直接引用:Array[i, j]
。同理,数组元素的更新涉及到三个参数:set_array(Array, vector(i, j), value)
,但是很多语言提供直接赋值:Array[i, j] = value
。
语法糖的例子
for循环
一个例子是C语言中的for循环:
for (i = 0; i < 10; i++) {
// P
}
其效果在不考虑for循环中的continue语句时和以下的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 salt)指的是不容易写出坏代码的语法特性。这些特性强迫程序员做出一些基本不用于描述程序行为,而是用来证明他们知道自己在做什么的额外举动。
语法糖精
语法糖精(英语:syntactic saccharine),或者说语法糖浆(英语:syntactic syrup),指的是未能让编程更加方便的附加语法[1][2]。
注释
- ↑ syntactic sugar. catb.org. [2015-08-03].
- ↑ Boiten, Eerke A.; Möller, Bernhard. Mathematics of Program Construction: 6th International Conference, MPC 2002, Dagstuhl Castle, Germany, July 8-10, 2002. Proceedings. Springer Science & Business Media. 2002-06-26: 93. ISBN 978-3-540-43857-1 (英语).
参考文献
- Abelson, Harold; Sussman, Gerald Jay; Sussman, Julie. Structure and Interpretation of Computer Programs. Cambridge, MA: MIT Press. 1996 [1984]. ISBN 0-262-51087-1.
- Landin, P. J. Correspondence between ALGOL 60 and Church's Lambda-notation: part I. Communications of the ACM. 1965-02, 8 (2): 89–101. ISSN 0001-0782. S2CID 6505810. doi:10.1145/363744.363749 (英语).
- Landin, Peter J. Programming Without Imperatives – An Example. UNIVAC Systems Programming Research. 1965-03.
- Landin, P. J. Getting rid of labels. Higher-Order and Symbolic Computation. 2009-12, 22 (4): 315–329. ISSN 1388-3690. doi:10.1007/s10990-010-9057-5 (英语).
- Landin, Peter J. A Generalization of Jumps and Labels. UNIVAC Systems Programming Research. 1965-08., reprinted in Landin, Peter J. A Generalization of Jumps and Labels. Higher-Order and Symbolic Computation. 1998-12-01, 11 (2): 125–143. CiteSeerX 10.1.1.85.2610 . ISSN 1573-0557. doi:10.1023/A:1010068630801 (英语).
- Perlis, Alan J. Special Feature: Epigrams on programming. ACM SIGPLAN Notices. 1982-09, 17 (9): 7–13. ISSN 0362-1340. S2CID 20512767. doi:10.1145/947955.1083808 (英语).