Roman Numerals with Prolog DCG and CLP(FD)
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 어 /
Reference
이 문제에 관하여(Roman Numerals with Prolog DCG and CLP(FD)), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/j4n_bur53/items/f4f38b3400fba6290fb0텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)