且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从文件中读取并使用 Prolog DCG 规则显示内容

更新时间:2023-02-23 18:55:02

你的程序有两个主要问题:1. 不允许在 classname/1 和 "{" 之间出现空格.由于实际上这里可能出现多个空格(和水平制表符),我使用了库 dcg/basics 中的 whites//0.2. phrase_from_file/2 尝试解析整个输入文档,而您的语法仅涵盖第一行(即类名).这是通过跳过文件的其余部分来解决的.我使用 '...'//0 然后 eos//0 为此.

There are two main problems with your program: 1. You do not allow for a space to occur between classname/1 and "{". Since in practice multiple spaces (and horizontal tabs) may occur here, I have used whites//0 from library dcg/basics. 2. phrase_from_file/2 tries to parse the entire input document, whereas your grammar only covers the first line (i.e., the class name). This is solved by skipping the rest of the file. I use '...'//0 and then eos//0 for this.

然后是一些小事:1. letters//1的子句在代码文件中没有连续放置.我重新定位了一个子句,但您也可以在程序顶部添加声明 :- discontiguous(letters//1)..2. 我已经使用 code_type/2 检查字母字符.

Then there are some minor things: 1. Clauses of letters//1 are not placed consecutively in the code file. I have relocated one clause but you can also add the declarations :- discontiguous(letters//1). at the top of your program. 2. I have used code_type/2 to check for alphabetic characters.

结果代码,根据来自 mat 的有用评论更新:

The resultant code, updated after useful comments from mat:

:- use_module(library(dcg/basics)).
:- use_module(library(pio)).

clas-s-rule(Z) -->
  "class",
  whites,
  classname(X),
  whites,
  "{",
  {name(Z,X)},
  ... .

classname([H|T])-->
  letter(H),
  letters(T).

letters([H|T])-->
  letter(H), !,
  letters(T).
letters([])--> [].

letter(X)-->
  [X],
  {code_type(X, alpha)}.

... --> [].
... -->
  [_],
  ... .

使用示例:

?- phrase_from_file(clas-s-rule(X), 'linesample.txt').
X = component