Search code examples
prologiterationbacktracking

Prolog - backtracking with iterator


I have a predicate like:

solve(parts(X), Places) :-
    "iterate Pl from Places to 0",
    tryPutPart(X, Pl),
    fail.

I want to force the backtracking there, because I want all the possible solutions.(Instead I would have found the place Pl recursively in different predicate).

Is it possible to do it somehow? I got the idea to make a list of length Places and looking like [1, 2, 3.....], and then try to non-deterministically putout some Y from it.

The behavior I would like is if I wrote places(0). places(1). places(2). - ... - and so on into code and then wrote it like

:- places(Y), tryPutPart(X, Y).

Solution

  • You can use the between/3 predicate to check all integers from a given range. For example:

    ?- between(1, 10, N), N > 3, write(N), nl, fail.
    4
    5
    6
    7
    8
    9
    10
    false.
    

    See http://www.swi-prolog.org/pldoc/doc_for?object=between/3 for SWI-Prolog documentation on this predicate.