In Prolog, can I choose solutions randomly?

If I have the following:

a(X) :- X = 1; X = 2; X = 3; X = 4.

I can make decisions in a deterministic order:

?- a(X).
X = 1 ;
X = 2 ;
X = 3 ;
X = 4.

Is there any method to ask the system to make decisions in a non-deterministic, random order? For instance:

?- a(X).
X = 4 ;
X = 1 ;
X = 3 ;
X = 2.

I know that I can find all solutions, and then select one randomly ( findall(X, a(X), Y), random_member(Z, Y).), but it is too expensive in my case.


Perhaps a clearer example:

p(X,Y,Z) :-
  (X = a; X = b; X = c; X = d),   % (D1)
  (Y = a; Y = b; Y = c),          % (D2)
  (Z = a; Z = b; Z = c; Z = d).   % (D3)

In deterministic construction, a solution X = d, Y = c, Z = dusing ?- p(X,Y,Z).will always go through 47 previous solutions ( 4 * 3 * 4 = 48). However, if the disjunctions are selected in a non-deterministic order, the system can choose X = din D1, Y = cin D2, Z = din D3, generating it as the first solution.

, AI, .

+4
1

, , , :

?

( , , , .)

, : !

, , :

p(X, Y, Z) :-
  (X = a; X = b; X = c; X = d),   % (D1)
  (Y = a; Y = b; Y = c),          % (D2)
  (Z = a; Z = b; Z = c; Z = d).   % (D3)

() , , , : (X = c ; X = b ; etc.), .

:

p(X, Y, Z) :-
    member(X, [a,b,c,d]),
    member(Y, [a,b,c]),
    member(Z, [a,b,c,d]).

, .

, :

p(X, Y, Z) :-
    random_member(X, [a,b,c,d]),
    random_member(Y, [a,b,c]),
    random_member(Z, [a,b,c,d]).

random_member(X, Ls0) :-
    random_permutation(Ls0, Ls),
    member(X, Ls).

:

?- p(X, Y, Z).
X = d,
Y = Z, Z = b ;
X = Z, Z = d,
Y = b ;
X = d,
Y = b,
Z = c ;
etc.

, , , : , , .. . , , , , .

, / , , Prolog, , , .

+1

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


All Articles