Capture the results of N backtracks

This is a simple question (I think) but I can’t find a good solution:

I want a predicate that captures the result of the first N backtracks of a goal or a closure (as opposed to all the backtracks as done by setof/3 and bagof/3):

capture(N, Template, Goal, Bag) :- …

for example, capturing 3 backtracks of length/2 called as length(L,LL) into a Bag using template [ L,LL ] would give [ [[],0], [[_7180],1], [[_10020, _11052],2] ]

(… and there seem to be “Cookbook” books for all sorts of Languages, demonstrating standard tricks, but there isn’t for Prolog. Or is there?)

See:
Pure and correct Prolog - what is it? (Creating Prolog Cookbook)

Barry’s Prolog
Reference Manual & User Guide - While not a Cookbook, it does have many practical examples.

2 Likes

Maybe you need limit/2 in library(solution_sequences)?

findall(L-N, limit(3, length(L, N)), R)
1 Like

You could use call_nth/2 as well as limit/2, but the syntax is rather unwield

?- findall([L,LL],(call_nth(length(L,LL),N),(N>3->!,fail;true)),R).
R = [[[], 0], [[_12141708], 1], [[_12141678, _12141684], 2]].
1 Like

Nice solutions. I was about to think about starting a Prolog engine to get at this.

A remark has been added to the SWI-Prolog manual page of between/3, which is, a bit awkwardly, classed under “special purpose integer arithmetic”, although (at least for me) the poodle’s kernel of it is really “control predicate”.