Random items in Prolog

Pieter picture Pieter · Feb 14, 2010 · Viewed 13.6k times · Source

I know I can do X is random(10). to get a random number from 0 to 10, but is there a similar command to get a random matching item?

Answer

Kaarel picture Kaarel · Feb 8, 2012

SWI-Prolog v6 has random_member/2 defined like this:

?- listing(random_member).
random:random_member(D, A) :-
    length(A, B),
    C is random(B),
    nth0(C, A, D).

Usage example:

?- random_member(a(N), [a(1), a(2), b(3)]).
N = 1.

?- random_member(a(N), [a(1), a(2), b(3)]).
N = 1.

?- random_member(a(N), [a(1), a(2), b(3)]).
N = 2.

?- random_member(a(N), [a(1), a(2), b(3)]).
false.

?- random_member(a(N), [a(1), a(2), b(3)]).
false.

?- random_member(a(N), [a(1), a(2), b(3)]).
N = 2.

You probably want to use it in the (-,+) mode though.