Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
rejection sampling conditioner in prolog
% Two dices are thrown and the results added up.
% We sample when the sum is conditioned on the first dice landing on 2.
output(S) :-
randvar(a, dice(X), X),
dice(Y),
S is X + Y.
dice(X) :-
X is random(6) + 1.
:- dynamic randvar/3.
randvar(_, Goal, _) :-
call(Goal).
sample_cond(N, Xs) :-
asserta((
randvar(a, Goal, X) :-
!,
call(Goal),
X = 2)),
sample_subcond(N, Xs).
sample_subcond(0, []).
sample_subcond(N, [X | Xs]) :-
repeat,
output(X),
K is N - 1,
sample_subcond(K, Xs).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment