Roman Numerals with Prolog DCG and CLP(FD)

5875 단어 PrologCLP(FD)DCG
The Prolog programming language implements the paradigma of logical variables from logic programming. Logical variables cannot be re-assigned a new value, they only go from uninstantiated to instantiated.

In a few situations this allows for bidirectional predicates. A typical example is the append predicate:
append([], X, X).
append([X|Y], Z, [X|T]) :- append(Y, Z, T).

We can run the predicate in mode append(+,+,-) to get:
?- append([1],[2,3],X).
X = [1,2,3]

Or we can run the predicate in mode append(-,-,+) to get:
?- append(X,Y,[1,2,3]).
X = [],
Y = [1, 2, 3] ;
X = [1],
Y = [2, 3]
Etc..

Whats more difficult, is programming bidirectional parsers/unparsers. We have taken an example originally written for SWI-Prolog by Michael Hendricks in 2015-07-10, and rewrote it so that it also runs on our own Prolog system.

The example takles the problem of converting Roman numerals into natural numbers back and forth. The code starts with a definite clause grammar (DCG) table of the Roman letters and their natural number values.

roman.pl
...
digit(10) --> "X".
digit(9) --> "IX".
digit(5) --> "V".
digit(4) --> "IV".
digit(1) --> "I".

The table already shows the core idea of ​​the solution. Namely to also tabulate some Roman letter combinations. As a next step we use a finite domain constraint solver (CLP(FD)) to code the conversion:

roman.pl
digits2(Total) -->
   {Rest #>= 0,
    Total #= Value+Rest},
   digit(Value),
digits2(Rest).

The CLP(FD) generalizes the concept of a Prolog logical variable, since it can attach arithmetic conditions to logical variables and therefore dynamically change the sub goal execution order. The end result is that we can use the grammar in both directions:



A nice little combination of DCG and CLP (FD).

Roman Numerals as a Prolog Package
htps : // 기주 b. 이 m / j 부 r 세 / 지 케 지 케 - mp ぇ s / t 어 /

좋은 웹페이지 즐겨찾기