Skip to content

Instantly share code, notes, and snippets.

@muupan
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save muupan/7f011fcc169e11704428 to your computer and use it in GitHub Desktop.
Save muupan/7f011fcc169e11704428 to your computer and use it in GitHub Desktop.
find_unique_n/4: Finding up to N unique solutions of a goal in Prolog (tested in Yet Another Prolog)
:- module(find_unique_n, [find_unique_n/4]).
:- meta_predicate find_unique_n(?,?,:,?).
:- use_module(library(ordsets)).
:- use_module(library(lists)).
find_unique_n(N, Term, Goal, Solutions) :-
N > 0,
( retractall(unique_solutions(_)),
assertz(unique_solutions([])),
once((
call(Goal),
retract(unique_solutions(_current_set)),
ord_union(_current_set, [Term], _next_set),
length(_next_set, _len),
assertz(unique_solutions(_next_set)),
_len =:= N
)),
fail
; retract(unique_solutions(Solutions))
).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment