LoginSignup
1
0

More than 3 years have passed since last update.

Roman Numerals with Prolog DCG and CLP(FD)

Last updated at Posted at 2019-05-16

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:

roman_numerals.png

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

Roman Numerals as a Prolog Package
https://github.com/jburse/jekejeke-samples/tree/master/pack/language

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0