语法糖

语法糖(英語: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這種「中置表示法」的語法,讓程式更容易撰寫,也比較容易閱讀。

运算符重载

C++提供了运算符重载,可以把運算符當作函式來寫,當使用運算子就等同於使用該函式,讓程式更容易撰寫,也比較容易閱讀。

關聯陣列

JavascriptLua中物件的「」如果不使用底線以外的符號、數字不做開頭時可以使用物件成員方式來取的「」。若不符合上述規則僅能使用陣列索引方式取得「值」。

以Javascript來舉例:

let a = { 'abc': 5, '12w': 6, '>': 7, '_': 8 };

console.log(a.abc);     //因為「鍵」符合規則,所以可以直接使用物件成員方式來取得「值」。
console.log(a["abc"]);  //也能用陣列索引的方式取得「值」。
console.log(a["12w"]);  //因為「鍵」是數字開頭,所以僅能以陣列索引方式取得「值」。
console.log(a[">"]);    //因為「鍵」有使用到符號,所以僅能以陣列索引方式取得「值」。
console.log(a._);       //雖然「鍵」有使用到符號,但是因為Javascript中底線可以當作變數名稱,所以可以使用物件成員方式來取得「值」。

差異在於如果使用陣列索引的話「鍵」需要加上「中括號」和「字串引號」,但是物件成員只要加上「小數點」能讓程式碼看起來更加簡潔。

衍生詞語

语法盐

语法盐(英語:syntactic salt)指的是不容易写出坏代码的语法特性。这些特性强迫程序员做出一些基本不用于描述程序行为,而是用来证明他们知道自己在做什么的额外举动。

语法糖精

语法糖精(英語:syntactic saccharine),或者说语法糖浆(英語:syntactic syrup),指的是未能让编程更加方便的附加语法[1][2]

註釋

參考文獻

Read other articles:

Jayprakash NarayanLahir(1902-10-11)11 Oktober 1902Sitabdiara, Kepresidenan Bengal, India Britania (sekarang di Saran, Bihar)Meninggal8 Oktober 1979(1979-10-08) (umur 76)Patna, BiharKebangsaanIndianNama lainJP, Lok NayakOrganisasiKongres Nasional IndiaPartai JanataGerakan politikKeluar IndiaSarwodayaGerakan JP Jayaprakash Narayan (simakⓘ; 11 Oktober 1902 – 8 Oktober 1979), yang lebih sering disebut sebagai JP atau Lok Nayak (Hindi untuk Pahlawan Rakyat), adalah seorang akti...

 

Sepeda lambat adalah salah satu lomba tradisional yang populer pada hari kemerdekaan Indonesia. Cara permainan Para peserta bersiap dengan sepeda masing-masing di garis permulaan dan berlomba untuk mencapai garis finish dalam lajur masing-masing. Namun, berbeda dan berlawanan dengan balap sepeda, pemenang sepeda lambat adalah peserta paling akhir yang mencapai garis finish. Karena sepeda hanya mempunyai dua roda, semakin lambat sepeda dikayuh, semakin sulit untuk menjaga keseimbangan, dan bil...

 

Use of psychedelic drugs as treatment Psychedelic therapy (or psychedelic-assisted therapy) refers to the proposed use of psychedelic drugs, such as psilocybin, MDMA,[note 1] LSD, and ayahuasca, to treat mental disorders.[2][3] As of 2021, psychedelic drugs are controlled substances in most countries and psychedelic therapy is not legally available outside clinical trials, with some exceptions.[3][4] The procedure for psychedelic therapy differs from th...

Igor Lediakhov Informasi pribadiNama lengkap Igor LediakhovTanggal lahir 22 Mei 1968 (umur 55)Tempat lahir Sochi, RusiaPosisi bermain PenyerangKarier senior*Tahun Tim Tampil (Gol)1988-1989 Rostov-on-Don 1990 Dnipro Dnipropetrovsk 1991-1992 Rotor Volgograd 1992-1994 Spartak Moscow 1994-2002 Sporting Gijón 1998 →Yokohama Flügels 2002-2003 Eibar Tim nasional1992 Uni Soviet 7 (1)1992-1994 Rusia 8 (0) * Penampilan dan gol di klub senior hanya dihitung dari liga domestik Igor Lediakhov (l...

 

Danish footballer (born 1984) Mariann Gajhede Personal informationFull name Mariann Gajhede KnudsenDate of birth (1984-11-16) 16 November 1984 (age 39)Place of birth Skagen, DenmarkHeight 1.78 m (5 ft 10 in)Position(s) MidfielderYouth career Skagen IKSenior career*Years Team Apps (Gls)2001 B52/Aalborg 2002–2010 Fortuna Hjørring 2011–2016 Linköpings FC 117 (10)International career‡2001–2003 Denmark U-19 24 (2)2003–2015 Denmark 107 (6) *Club domestic league appea...

 

American metalcore band The Dillinger Escape PlanThe Dillinger Escape Plan at With Full Force 2014. From left to right: Greg Puciato, Billy Rymer behind Liam Wilson, and James Love (Ben Weinman not shown).Background informationOriginMorris Plains, New Jersey, USGenres Mathcore metalcore experimental metal progressive metal Years active 1997–2017 2023–present Labels Relapse Party Smasher Members Ben Weinman Dimitri Minakakis Liam Wilson James Love Billy Rymer Past members Greg Puciato Kevi...

Attempt to redistribute land during the US Civil War For the film production company, see 40 Acres and a Mule Filmworks. General William T. Sherman, who issued the orders that were the genesis of forty acres and a mule. Forty acres and a mule was part of Special Field Orders No. 15, a wartime order proclaimed by Union General William Tecumseh Sherman on January 16, 1865, during the American Civil War, to allot land to some freed families, in plots of land no larger than 40 acres (16 ha)....

 

Natrium borohidrida Nama Nama IUPAC (preferensi) Natrium tetrahidridoborat (1–) Nama IUPAC (sistematis) Natrium boranuida Penanda Nomor CAS 16940-66-2 Y15681-89-7 (2D4) Y Model 3D (JSmol) Gambar interaktif 3DMet {{{3DMet}}} ChEBI CHEBI:50985 Y ChemSpider 26189 Y9052313 (2D4) Y9312193 (3T4) Y Nomor EC Referensi Gmelin 23167 MeSH Sodium+borohydride PubChem CID 431176423673181 (2D4)23671303 (3T4) Nomor RTECS {{{value}}} Nomor UN 1426 Comp...

 

French Jesuit martyrs Canadian MartyrsHoly card depicting the martyrsBornFranceDied17th century, Canada and Upstate New YorkMartyred byIroquoisVenerated inRoman Catholic Church Anglican ChurchBeatifiedJune 21, 1925, Rome, by Pope Pius XICanonizedJune 29, 1930, Rome, by Pope Pius XIMajor shrineMartyrs' Shrine, Midland, Ontario, Canada National Shrine of the North American Martyrs, Auriesville, New YorkFeastSeptember 26 (in Canada and among Traditional Roman Catholics)October 19 (General Calend...

Norwegian footballer and coach (born 1955) Arne Dokken Personal informationFull name Arne DokkenDate of birth (1955-08-27) 27 August 1955 (age 68)Place of birth Drammen, NorwayPosition(s) ForwardYouth career Åssiden IFSenior career*Years Team Apps (Gls)1975–1977 Strømsgodset 43 (26)1978–1981 Lillestrøm SK 79 (35)1981–1983 Panathinaikos 23 (10)1983–1984 Apollon Smyrnis 24 (6)1984–1986 Rosenborg 25 (5)International career1975–1984[1] Norway 24 (2)Managerial career198...

 

Sculpture in Manhattan, New York, U.S. Eagles and PreyThe sculpture in 2010ArtistChristophe FratinYear1850 (1850)TypeSculptureMediumBronzeSubjectLiberty of AmericaLocationNew York City, New York, United StatesCoordinates40°46′18″N 73°58′23″W / 40.77167°N 73.97308°W / 40.77167; -73.97308 Eagles and Prey is an outdoor bronze sculpture by Christophe Fratin, located in Central Park in Manhattan, New York. Created in 1850 and installed in Central Park in 18...

 

此条目序言章节没有充分总结全文内容要点。 (2019年3月21日)请考虑扩充序言,清晰概述条目所有重點。请在条目的讨论页讨论此问题。 哈萨克斯坦總統哈薩克總統旗現任Қасым-Жомарт Кемелұлы Тоқаев卡瑟姆若马尔特·托卡耶夫自2019年3月20日在任任期7年首任努尔苏丹·纳扎尔巴耶夫设立1990年4月24日(哈薩克蘇維埃社會主義共和國總統) 哈萨克斯坦 哈萨克斯坦政府...

Count of Burgundy Otto IVSeal of Otto IVCount of BurgundyReign8 March 1279 – 17 March 1303PredecessorAdelaideSuccessorJoan IIBornc. 1248OrnansDied17 March 1303MelunSpousePhilippa of BarMahaut of ArtoisIssueJoan II, Countess of BurgundyBlanche, Queen of FranceRobert of BurgundyHouseHouse of IvreaFatherHugh de ChâlonMotherAdelaide, Countess Palatine of Burgundy Otto IV (1248, in Ornans – 17 March 1303, in Melun[1]) was the count of the Free County of Burgundy from 1279 until 1303. ...

 

Religion in Cameroon Muslims in Cameroon The palace of the sultan of the Bamun people at Foumban, West Region Islam by countryWorld percentage of Muslims by country Africa Algeria Angola Benin Botswana Burkina Faso Burundi Cameroon Cape Verde Central African Republic Chad Comoros Democratic Republic of the Congo Republic of the Congo Djibouti Egypt Equatorial Guinea Eritrea Eswatini Ethiopia Gabon Gambia Ghana Guinea Guinea-Bissau Ivory Coast Kenya Lesotho Liberia Libya Madagascar Malawi Mali...

 

German chemist (1902–1980) Fritz StrassmannBornFriedrich Wilhelm Strassmann22 February 1902Boppard, German EmpireDied22 April 1980 (aged 78)Mainz, West GermanyNationalityGermanEducationTechnical University of HannoverKnown forCo-discovery of Nuclear fissionAwardsEnrico Fermi Award (1966)Scientific careerFieldsPhysicist, ChemistInstitutionsKaiser-Wilhelm InstitutesUniversity of MainzDoctoral advisorHermann Braune RighteousAmong the Nations The Holocaust Rescuers of Jews Righteousness Se...

Territorial dispute between Argentina and the United Kingdom Timeline of de facto control April 1764– February 1767  France January 1765– July 1770  Great Britain February 1767– February 1811  Spain September 1771– May 1774  Great Britain February 1811– August 1829 None August 1829– December 1831  United Provinces of the Río de la Plata December 1831– January 1832  United States January–December 1832 None December 1832– January 1833  Argen...

 

Arts charity in the UK Art UKFormation2003TypeCharityPurposeTo create a complete digital record of the UK's collection of oil, tempera and acrylic paintings and sculpture and to make art accessible to the public.LocationMonument, LondonRegion served United KingdomWebsiteartuk.org Art UK is a cultural, education charity in the United Kingdom,[1] previously known as the Public Catalogue Foundation. Since 2003, it has digitised more than 300,000 paintings, sculptures and other artworks b...

 

Pep rally event at Texas A&M University Midnight Yell Practice, known locally as Midnight Yell or Yell Practice, is a tradition at Texas A&M University. Midnight Yell is similar to a pep rally. On the night before each home football game, Midnight Yell takes place in Kyle Field at midnight; two nights before each away game, a Yell Practice (not at midnight) is held near the Quadrangle on the south side of campus. At midnight on the night before an away game Midnight Yell is held in or...

Chemical compound LefetamineClinical dataRoutes ofadministrationOralATC codenoneLegal statusLegal status AU: S4 (Prescription only) BR: Class B1 (Psychoactive drugs)[1] CA: Schedule III DE: Anlage I (Authorized scientific use only) UK: Class B US: Schedule IV Identifiers IUPAC name (1R)-N,N-dimethyl-1,2-diphenylethanamine CAS Number7262-75-1 NPubChem CID443970ChemSpider392017 YUNII4J9726V5Y9CompTox Dashboard (EPA)DTXSID7046833 Chemical and physi...

 

Chemical compound AsciminibClinical dataTrade namesScemblixOther namesABL001License data US DailyMed: Asciminib Pregnancycategory AU: D[1][2] Routes ofadministrationBy mouthDrug classTyrosine kinase inhibitorATC codeL01EA06 (WHO) Legal statusLegal status AU: S4 (Prescription only)[1] CA: ℞-only[3][4] US: ℞-only[5] EU: Rx-only[6] Identifiers IUPAC name N-4-[chloro(difluoro)methoxy]phenyl]-...