Search code examples
prologbacktracking

Prevent backtracking of function


Is it possible to specify to not backtrack a certain function? For example with the following code the somestatisticalfunction could be assumed to always be correct, and does not need to be backtracked. So when backtracking I would want Prolog to only backtrack the dosomethingelse(Output) and length(Ls, Size).

f(Ls) :-
    length(Ls, Size),
    somestatisticsalfunction(Size, Output), % Don't backtrack this
    dosomethingelse(Output).

Solution

  • Instead of:

    somestatisticsalfunction(Size, Output),
    

    use:

    once(somestatisticsalfunction(Size, Output)),
    

    to succeed at most once. See https://www.swi-prolog.org/pldoc/man?predicate=once/1

    I would also look at improving somestatisticsalfunction to prevent unwanted choicepoints.