簡體   English   中英

Prolog DCG 中的可選或重復項

[英]Optional or Repeated Items in Prolog DCG

所以我正在使用 Definite Clause Grammars 在 SWI-Prolog 中為 Pascal 編寫一個簡單的解析器。

我不明白如何實現重復(2 個或更多)或可選地重復(1 個或更多)謂詞。

例如,在 EBNF 中,對於 Pascal 的“程序”是:

"PROGRAM" identifier "(" identifierlist ")" ";" block "."

其中“標識符列表”是:

identifier { "," identifier }

“標識符”是:

letter { letter | digit }

我知道在 prolog 的 DCG 表單程序中是:

program --> ["PROGRAM"], identifier, ["("], identifierlist, [")"], [";"], block, ["."].

我如何實現“標識符列表”甚至“標識符”,其中包含可選的重復數量的“標識符”或“字母”或“數字”謂詞?

在 Prolog 中,只要 EBNF 確實是您想要的,您就可以完全按照 EBNF 來編寫它。

identifierlist = identifier { "," identifier }

你也可以這樣寫:

identifierlist = identifier
identifierlist = identifier , identifierlist

在 Prolog 中,您可以這樣寫:

identifier_list --> identifier.
identifier_list --> identifier, ",", identifier_list.

如果你想包含一個空的標識符列表,那么它會更詳細一些:

identifier_list --> [].
identifier_list --> nonempty_identifier_list.

nonempty_identifier_list--> identifier.
nonempty_identifier_list--> identifier, ",", nonempty_identifier_list.

您的原始 EBNF 不包含空標識符列表。 如果是這樣,上面的代碼可能看起來很像 EBNF。


正如@false 在評論中指出的那樣, nonempty_identifier_list的另一種呈現方式是:

 nonempty_identifier_list --> identifier, ( [] | ",", nonempty_identifier_list ).

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM