S-表达式

Tree data structure representing the s-expression for (* 2 (+ 3 4))

所谓“S-表达式/運算式”(S-expression)或“sexp”(其中“S”代表“符号的”),是指一种以人类可读的文本形式表达半结构化数据的约定。S-表达式可能以其在Lisp家族的编程语言中的使用而为人所知。其他应用则见于由Lisp衍生的语言,如DSSSL英语Document Style Semantics and Specification Language,以及如IMAP之类通信协议中作为标记出现和约翰·麦卡锡CBCL英语Common Business Communication Language。语法细节和所支持的数据类型虽因语言而异,但这些语言间最通用的特性则是使用S-表达式作为括号化的前缀表示法(有时亦作剑桥波兰表示法)。

數據類型和語法

S-表達式格式有許多變體,支持不同數據類型的各種不同語法。最廣泛支持的是:

  • 列表和點對: (1 () (2 . 3) (4))
  • 符號: with-hyphen ?@!$ a\ symbol\ with\ spaces
  • 字串: "Hello, world!"
  • 整數: -9876543210
  • 浮點數: -0.0 6.28318 6.023e23

在 LISP 編程中使用

S-表达式在Lisp中既用作代码,也用作数据(见McCarthy Recursive Functions of Symbolic Expressions[1])。S-表达式原本被用于将被M-表达式英语M-expression处理的数据,但Lisp的首个实现是一个 S-表达式的解释器,以 S-表达式编码 M-表达式,而Lisp程序员很快习惯于对代码和数据都使用 S-表达式。

S-表达式可以是如数字这样的单个对象,包括特殊原子nilt在内的LISP 原子英语LIST atom,或写作 (x . y)cons pair。更长的列表则由嵌套的cons pair组成,例如(1 . (2 . (3 . nil)))(,亦可写作更易理解的(1 2 3))。

使用前缀表示法,程序代码可写作 S-表达式。书写Lisp程序中额外的语法糖则是,一般的表达式(quote x)可以省略为'x

數據表達式的示例

嵌套列表可以寫為 S-表達式:((milk juice) (honey marmalade))是一個雙元素S-表達式,其元素也是雙元素 S-表達式。Lisp(和本文)中使用的以空格分隔的符號是典型的。換行符(換行符)通常有資格作為分隔符。 這是一個簡單的上下文無關語法的一小部分英語寫成 S-表達式(Gazdar / Melish,Lisp 中的自然語言處理):

(((S) (NP VP))
 ((VP) (V))
 ((VP) (V NP))
 ((V) died)
 ((V) employed)
 ((NP) nurses)
 ((NP) patients)
 ((NP) Medicenter)
 ((NP) "Dr Chan"))

S 表達式的源碼示例

Common Lisp范例:

(defun factorial (x)
    (if (zerop x) 1
        (* x (factorial (- x 1)))))

Scheme范例:

(define (factorial x)
    (if (zero? x) 1
        (* x (factorial (- x 1)))))

解析

S-表達式經常與 XML 進行比較,一個關鍵的區別是 S-表達式在語法上要簡單得多,因此更容易解析。例如,可以在幾十行 Python 代碼中實現一個簡單的 S-表達式解析器。

def parse_sexp(string):
    """
    >>> parse_sexp("(+ 5 (+ 3 5))")
    [['+', '5', ['+', '3', '5']]]
    
    """
    sexp = [[]]
    word = ''
    in_str = False
    for char in string:
        if char == '(' and not in_str:
            sexp.append([])
        elif char == ')' and not in_str:
            if word:
                sexp[-1].append(word)
                word = ''
            temp = sexp.pop()
            sexp[-1].append(temp)
        elif char in (' ', '\n', '\t') and not in_str:
            if word:
                sexp[-1].append(word)
                word = ''
        elif char == '\"':
            in_str = not in_str
        else:
            word += char
    return sexp[0]

標準化

1997年5月,罗纳德·李维斯特 提交了一份 Internet-Draft英语Internet-草案 ,拟作为RFC出版。该草案定义了基于Lisp S-表达式的语法,但旨在用于一般目的的数据存储及交换(类似XML)而非仅限于编程。尽管未被批准为RFC,但此草案已被其他RFC(如RFC 2693)和数种出版物[2]引用。最原始的用途则是在SPKI英语Simple public key infrastructure中。

Rivest的格式定义了 S-表达式为一个八位元组-串(一系列字节)或其他S-表达式的有限列表。此定义描述了三种表达这种结构的互换格式。一种为“advanced transport”——以格式而言具有很大弹性,且语法上近似于Lisp-风格表达式,但并不等同。例如,advanced transport允许八位元组-串逐字表示(串的长度后跟随一分号及整个原始的串),引号形式允许转义字符,十六进制Base64,或者在满足一定条件时直接作为“token”。(Rivest的token与Lisp token不同之处在于前者仅仅为了方便与审美,像其他字符串一样对待,而后者有特别的语法意义。)为了更为紧密,更便于语法分析,独立于任何抽象的 S-表达式,另一种交换格式“canonical presentation”仅允许逐字表示的字符串,格式上禁止字符串以外的空白。

相关条目

引用

外部链接

自由软件

Read other articles:

Piala IslandiaMulai digelar1960Wilayah IslandiaJumlah tim66Juara bertahanVikingurTim tersuksesKR (14 gelar) Piala Islandia 2023 Piala Islandia adalah kejuaraan nasional sepak bola di Islandia. Mulai diselenggarakan sejak 1960, pemenangnya berhak mengikuti Liga Eropa UEFA pada musim berikutnya. Daftar juara 1960: KR 1961: KR 1962: KR 1963: KR 1964: KR 1965: Valur 1966: KR 1967: KR 1968: ÍBV 1969: ÍBA 1970: Fram 1971: Víkingur 1972: ÍBV 1973: Fram 1974: Valur 1975: Keflavik 1976: Valur...

 

Secret headquarters of the fictional DC Comics superhero Batman For other uses, see Batcave (disambiguation). BatcaveBatman locationThe Batcave in Batman (vol. 2) #1 (November 2011)Art by Greg CapulloCreated byHarry L. FraserGenreSuperhero comicsIn-universe informationTypeUnderground laboratoryLocationsWayne ManorCharactersBatmanRobinAlfred PennyworthHarold AllnutAce the Bat-HoundBatgirlThe OutsidersPublisherDC Comics The Batcave is a subterranean location appearing in American comic books pu...

 

Chevrolet C/K Appelé aussi GMC C/KGMC Sierra Marque Chevrolet Années de production 1960 - 2001 Production 3 293 598 exemplaire(s) Classe Utilitaire ;Pour modèles poids lourds : Porteur, Tracteur routier, Autobus Moteur et transmission Énergie essence Transmission Propulsion (C-Series) ou intégrale (K-Series) Châssis - Carrosserie Carrosserie(s) Pick-up (modèles légers)Camionnette tôlée (certains modèles légers, jusqu'en 1970)Camion à ridellesChâssis-cab...

Cet article est une ébauche concernant un coureur cycliste allemand. Vous pouvez partager vos connaissances en l’améliorant (comment ?). Pour plus d’informations, voyez le projet cyclisme. Pour les articles homonymes, voir Rich. Michael RichMichael RichInformationsNaissance 23 septembre 1969 (54 ans)Fribourg-en-BrisgauNationalité allemandeSpécialité RouleurÉquipes amateurs 1994Histor ÖschelbronnÉquipes professionnelles 09.1994-12.1994Telekom-Merckx (Stagiaire)1997-1998S...

 

American Founding Father and politician (1734–1817) For other people named Thomas McKean, see Thomas McKean (disambiguation). Thomas McKeanPortrait by Charles Willson Peale2nd Governor of PennsylvaniaIn officeDecember 17, 1799 – December 20, 1808Preceded byThomas MifflinSucceeded bySimon SnyderChief Justice of the Pennsylvania Supreme CourtIn officeJuly 28, 1777 – December 17, 1799Preceded byBenjamin ChewSucceeded byEdward Shippen IV8th President of the Continental Con...

 

This article is about the city in Bihar, India. For other uses, see Arrah (disambiguation). City in Bihar, IndiaArrah AraCityAraProminent places of AraArrahLocation in Bihar, IndiaCoordinates: 25°33′05″N 84°39′37″E / 25.55139°N 84.66028°E / 25.55139; 84.66028Country IndiaStateBiharDivisionPatnaDistrictBhojpurNamed forAranya DeviGovernment • TypeMunicipal Corporation • BodyArrah Municipal Corporation • MayorIndu Devi&...

Artikel ini tidak memiliki referensi atau sumber tepercaya sehingga isinya tidak bisa dipastikan. Tolong bantu perbaiki artikel ini dengan menambahkan referensi yang layak. Tulisan tanpa sumber dapat dipertanyakan dan dihapus sewaktu-waktu.Cari sumber: Kasrah – berita · surat kabar · buku · cendekiawan · JSTOR Huruf yang berharakat kasrah Kasrah (Arab: (كسرة) , kasrat) adalah harakat yang berbentuk layaknya garis horizontal kecil (ِ) yang diletakk...

 

This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Riegelsville, Pennsylvania – news · newspapers · books · scholar · JSTOR (January 2023) (Learn how and when to remove this message) Borough in Pennsylvania, United StatesRiegelsville, PennsylvaniaBoroughSigns on the approach for the Riegelsville Bridge denoting...

 

Cristóbal López RomeroS.D.B.Uskup Agung RabatGerejaGereja KatolikKeuskupan agungRabatTakhtaRabatPenunjukan29 Desember 2017Awal masa jabatan10 Maret 2018PendahuluVincent Louis Marie LandelJabatan lainAdministrator Apostolik Tanger (2019-)Kardinal-Imam San Leone I (2019-)ImamatTahbisan imam19 Mei 1979oleh Narciso Jubany ArnauTahbisan uskup10 Maret 2018oleh Juan José OmellaPelantikan kardinal5 Oktober 2019oleh Paus FransiskusPeringkatKardinal-ImamInformasi pribadiNama lahirCristóba...

Liquid hydrogen/oxygen rocket engine Blue Engine 3 (BE-3)Country of originUnited StatesManufacturerBlue OriginStatusActivePerformanceThrustBE-3PM: 49.8 tf (0.488 MN; 110,000 lbf) (sea level) BE-3U: 72.5 tf (0.711 MN; 160,000 lbf) (vacuum)Throttle range18-100%Used inNew Shepard, New Glenn The BE-3 (Blue Engine 3) is a LH2/LOX rocket engine developed by Blue Origin. The engine began development in the early 2010s, and completed acceptance testing in early 2015. The...

 

درع المجتمع الإنجليزي 2017 تفاصيل الموسم درع المجتمع الإنجليزي  النسخة 95  البلد المملكة المتحدة  المنظم الاتحاد الإنجليزي لكرة القدم  البطل نادي آرسنال  مباريات ملعوبة 1   عدد المشاركين 2   الحضور الجماهيري 83325   درع المجتمع الإنجليزي 2016  درع المجتمع ال�...

 

Sir Frederick Gowland HopkinsLahir(1861-06-20)20 Juni 1861Eastbourne, East Sussex, InggrisMeninggal16 Mei 1947(1947-05-16) (umur 85)Cambridge, Cambridgeshire, InggrisKebangsaanBritania RayaDikenal atasPenemuan vitamin, triptofanPenghargaan Nobel Kedokteran (1929)Karier ilmiahBidangBiokimiaInstitusiUniversitas CambridgePembimbing doktoralThomas StevensonMahasiswa doktoralJ.B.S. HaldaneJudah Hirsch QuastelMalcolm Dixon Sir Frederick Gowland Hopkins OM FRS (20 Juni 1861 – 1...

Icelandic bank Íslandsbanki hf.Company typePrivateIndustryBankingPredecessorGlitnir banki hf.Founded15 October 2008(history traces back to 1884)HeadquartersReykjavík, IcelandNumber of locations12 branches (2023)33 ATMs (2023)Area servedIcelandKey peopleJón Guðni Ómarsson(CEO)Fridrik Sophusson(Chairman)ProductsConsumer banking, corporate banking, mortgage loans, private banking, private equity, wealth management, credit cards,Revenue ISK 44.189 billion (2017)[1]Operating inco...

 

外来種(がいらいしゅ)とは、もともとその地域にいなかったのに、人為的に他の地域から入ってきた生物のこと[1]。アレロパシーが強い植物、など、その一部は生態系や経済に重大な影響を与える際には、環境問題のひとつとして扱われる[2]。ただ、飼育や畑などといった、管理している区域は除く。 類義語に移入種、帰化種、侵入種、外来生物がある。...

 

2018 United States Senate election in Wisconsin ← 2012 November 6, 2018 (2018-11-06) 2024 → Turnout61.2%   Nominee Tammy Baldwin Leah Vukmir Party Democratic Republican Popular vote 1,472,914 1,184,885 Percentage 55.36% 44.53% County results Congressional district results Precinct resultsBaldwin:      40–50%      50–60%      60–70%      70�...

The counter of the letter 'p' shown in red In typography, a counter is the area of a letter that is entirely or partially enclosed by a letter form or a symbol (the counter-space/the hole of).[1][2] The stroke that creates such a space is known as a bowl.[3] Latin letters containing closed counters include A, B, D, O, P, Q, R, a, b, d, e, g, o, p, and q. Latin letters containing open counters include c, f, h, s etc. The digits 0, 4, 6, 8, and 9 also have counters. An a...

 

French politician (1928–2020) Christian PonceletPresident of the French SenateIn office2 October 1998 – 30 September 2008Preceded byRené MonorySucceeded byGérard Larcher Personal detailsBorn(1928-03-24)24 March 1928Blaise, ArdennesDied11 September 2020(2020-09-11) (aged 92)Remiremont, FrancePolitical partyUMPSpouse Yvette Miclot ​ ​(m. 1949; died 2019)​Children2 Christian Poncelet (French pronunciation: [kʁistjɑ̃ pɔ̃...

 

Species of gastropod Partula varia Live Partula varia at Marwell Zoo. Shell of Partula varia glutinosa. Conservation status Extinct in the Wild  (IUCN 3.1)[1] Scientific classification Domain: Eukaryota Kingdom: Animalia Phylum: Mollusca Class: Gastropoda Subclass: Heterobranchia Order: Stylommatophora Family: Partulidae Genus: Partula Species: P. varia Binomial name Partula variaBroderip, 1832 Partula varia is a species of air-breathing tropical land snail, a terrestrial pu...

Australian actress (born 1998) Lara RobinsonBorn (1998-01-01) 1 January 1998 (age 26)Melbourne, Victoria, AustraliaOccupation(s)Actress, SingerYears active2006–present Lara Robinson (born 1 January 1998) is an Australian actress who has appeared in films, television series, and theatre productions. Career Robinson has appeared in a remake of a 1978 Australian thriller Long Weekend starring Claudia Karvan as well as an American science fiction drama, Knowing, starring Nicolas Cage ...

 

Railway branch line in Buckinghamshire, UK Wolverton–Newport Pagnell linePlatform at the former Bradwell station. The trackbed is now a shared use pathOverviewLocaleEnglandDates of operation1866–1967SuccessorAbandonedTechnicalTrack gauge1,435 mm (4 ft 8+1⁄2 in)Length4 miles (6.4 km) vteWolverton–Newport Pagnell line Legend Newport Pagnell Great Linford Bradwell Wolverton West CoastMain Line The Wolverton–Newport Pagnell line was a railway b...