Question

I am trying to create a program that displays a solution to a problem and I need a way to display the solution that it created. I have two operations that can be used to solve the problem though and the order in which they are called matters.

test(a) :- write('use a ').
test(b) :- write('use b '), fail.

test(c) :- test(a), test(b), test(a).
test(c) :- test(a), test(a).

Please note this is an example and should not be taken literally. Think of test(a) and test(b) as the operations and test(c) as the function that's checking which order would be valid.

Now test(c). will print even the ones that fails. Resulting in output "use a use b use a use a".

Was it helpful?

Solution 2

Your problem seems a legitimate call for assertz/retract.

These builtins allow to track the chronological sequence, and to store arbitrary Prolog terms, then you could write

:- dynamic results/2.

test(a) :- a_code(Result), assertz(results(a, Result)).
test(b) :- b_code(Result), assertz(results(b, Result)).

test(c) :- test(a), test(b), test(a).
test(c) :- test(a), test(a).

check_results :- forall(retract(Name, Result), writeln(Name = Result)).

If you want to track failed executions, you can extend that schema:

test(a) :- a_code(Result) -> assertz(results(ok(a), Result)) ; assertz(results(ko(a), _)).
test(b) :- b_code(Result) -> assertz(results(ok(b), Result)) ; assertz(results(ko(b), _)).

OTHER TIPS

Instead of using side effects, consider using a DCG that describes the list of goals. Your example can be easily turned into a DCG with a few mechanical rewriting steps, for example:

test(a) --> ['use a'].
test(b) --> ['use b'], { false }.

test(c) --> test(a), test(b), test(a).
test(c) --> test(a), test(a).

Then you can query:

?- phrase(test(c), Ls).
Ls = ['use a', 'use a'].

When you have such a list Ls, you can easily write it in any way you want. Notice though that the toplevel already prints each solution in a useful way, and there may be little reason to do so yourself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top