'Prolog: Code Generation

What's the most idiomatic approach to output prolog code from a prolog program (as a side effect)?

For instance, in a simple case, I might want to write a Program that, given a text input, yields another Prolog program representing the text as a directed graph.

I understand this question is somewhat vague, but I've resigned to consulting Stackoverflow after failing to find a satisfying answer in the available Prolog Meta-Programming literature, which mostly covers applications of meta-circular interpreters.

If you feel this question might be better articulated some other way, please edit it or leave a comment.



Solution 1:[1]

The most idiomatic way is always to stay pure and avoid side effects.

Let the toplevel do the writing for you!

To generate a Prolog program, you define a relation that says for example:

program(P) :- ...

and then states, in terms of logical relations, what holds about P.

For example:

program(P) :-
        P = ( Head :- Body ),
        Head = head(A, B),
        Body = body(A, B).

Example query and answer:

?- program(P).
P =  (head(_G261, _G262):-body(_G261, _G262)).

So, there's your program, produced in a pure way.

If you want to write it, use portray_clause/1:

?- program(P), portray_clause(P).
head(A, B) :-
        body(A, B).
...

This can be useful in a failure driven loop, to produce many programs automatically.

Solution 2:[2]

writeq/1 (or format('~q', [...])) produces output that can be read back. Usually you need also to put a full stop after a clause body. For instance, try

?- A_Clause = (X is 1+Y, write('X is '), write(X), nl), format('~q.~n', [A_Clause]).

Readability of code suffers from loosing variables 'nice names', but the functionality is there...

edit

as noted by @false, a space before the dot will avoid a bug in case the output term would finish with a dot

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mat
Solution 2 Erik Kaplun