Prolog: obtaining predicate decisions and asserting them as facts

I have a specific problem, but I’m just trying to come up with a general question so that other people can benefit from it ...

I have a predicate that returns many solutions, i.e.

X=5; X=2; X=7

and I want the predicate to get each of these decisions and state them as Prolog facts, so in the end I get three facts, for example.

fact(5) fact(2) fact(7)

therefore, the call fact(5)will be true, but the call fact(8)will be false, because we never claimed it, because it was not a solution.

But I do not want to have a predicate in which you must continue to propose solutions for the statement of each individual fact. I want to call a predicate, and let it go through all the decisions in the background, approve them and that.

One way to solve this problem is to use findall to place all the solutions in the list, and then just view the list containing all the elements of the list. However, I do not think it is very elegant. There should be a nicer way to do this without messing with lists.

+3
source share
2 answers

Use a failover loop to force a return on all solutions:

?- computation(X), false.

You can ignore this request with a declaratively false true with ignore / 1:

?- ignore((computation(X),false)).
+4
source

This function can be performed using setof and creating a second-order predicate.

:- dynamic fact/1.

isAns(5).
isAns(2).
isAns(7).

computation(F) :- setof(X,call(F,X),S),factify(S).

factify([X|Xs]) :- assert(fact(X)),factify(Xs).
factify([]).

Then, when we go and ask about the facts, we get:

computation(isAns), fact(X).
X = 5;
X = 2;
X = 7;
false 
+3
source

Source: https://habr.com/ru/post/1777289/


All Articles