Prolog - Multiplying A list with an uninstantiated list - prolog

The input to this predicate is S, a list of integers I, and a list of integers T. Assumption is that both S and I are fully instantiated, but not T. The function multiplies the the first element in I with the first element in T then sums it with the second element in I multiplied with the [...] you get the idea. However, the struggle I am having is making this function succeed when T isn't instantiated it. I don't want to use use_module(library(clpfd)) even though it may be easier.
I already have something which multiplies correctly, as a helper. To get rid of the "uninstantiated variable" issue I figured I let a variable = S div head of I, so I'd instantiate a new variable, and I'd do this for each item in list I. Then I'd generate all the permutations such that the multiplication of items in a list summed results to S
mult_prod(A, B, S) :-
sum_prod(A, B, 0, S).
mult_prod([A | As], [B | Bs], Accum, S) :-
Accum1 is Accum + A*B,
mult_prod(As, Bs, Accum1, S).
mult_prod([], [], Accum, Accum).
multSum(S, I, T) :-

My naive solution:
multSum(0, [], []).
multSum(S, [I | Is], [T | Ts]) :-
between(0, S, T),
S1 is S - I * T,
multSum(S1, Is, Ts).
Sample output:
?- multSum(42, [6, 7, 8, 9], T).
T = [0, 0, 3, 2] ;
T = [0, 1, 1, 3] ;
T = [0, 6, 0, 0] ;
T = [1, 0, 0, 4] ;
T = [1, 4, 1, 0] ;
T = [2, 2, 2, 0] ;
T = [2, 3, 0, 1] ;
T = [3, 0, 3, 0] ;
T = [3, 1, 1, 1] ;
T = [4, 0, 0, 2] ;
T = [7, 0, 0, 0] ;
false.
Potential problems:
This was just too easy; I must have overlooked something in your question or totally misinterpreted it.
Tested in SWI Prolog only; relies on between/3. If necessary, you can implement this predicate yourself.
Limited to non-negative numbers.
Exhaustively generates all possibilities, which can be quite a lot.
Probably not the most efficient implementation possible...

Related

Write a program in prolog that determines if there are exactly three values in such a way that they add upto a sum of N

Eg:
List[1,2,3,4,5,6] with N equal to 6 should print true because there are exactly 3 values that add upto 6. 1+2+3.
List[2,5,7,9] with N equal to 12 should print false as there are no 3 elements that add upto 12.
Let's maybe start with a more general predicate that describes the relation between a list, a sublist of said list and the sum of numbers in the sublist. To make it obvious which argument is what, it is opportune to chose a descriptive name for the predicate, say sum_ofsub_fromlist/3. Now let's observe that if the first argument is the sum of the numbers in the sublist, then successively subtracting those numbers from the sum yields zero, e.g.: X=A+B → X-A-B=0. So there will be a base case that contains 0 as the sum and [] as the sublist (rule 1) and a recursive rule that subtracts the elements of the sublist from the sum (rule 2). And since a sublist does not contain all elements of the list it's taken from in general, there will be a recursive rule for skipping elements of the list that do not occur in the sublist (rule 3). This rule is only needed as long as there are still elements in the sublist, so a constraint would be beneficial, that prevents this rule from succeeding once the sublist is empty. These ideas can be realized in Prolog like so:
sum_ofsub_fromlist(0,[],_L). % rule 1
sum_ofsub_fromlist(X,[A|Bs],[A|As]) :- % rule 2
X0 is X-A,
sum_ofsub_fromlist(X0,Bs,As).
sum_ofsub_fromlist(X,Bs,[_A|As]) :- % rule 3
dif(Bs,[]), % constraint: sublist not empty
sum_ofsub_fromlist(X,Bs,As).
You can query this predicate to assure yourself that it delivers all sublists for the given sum in your examples:
?- sum_ofsub_fromlist(6,S,[1,2,3,4,5,6]).
S = [1, 2, 3] ;
S = [1, 5] ;
S = [2, 4] ;
S = [6] ;
false.
?- sum_ofsub_fromlist(12,S,[2,5,7,9]).
S = [5, 7] ;
false.
Building on this you can then write a calling predicate that only succeeds for sublists of length three:
sum_oftriple_fromlist(S,T,L) :-
T=[_,_,_], % T has to be a triple
sum_ofsub_fromlist(S,T,L).
This predicate yields the answers you desire:
?- sum_oftriple_fromlist(6,T,[1,2,3,4,5,6]).
T = [1, 2, 3] ;
false.
?- sum_oftriple_fromlist(12,T,[2,5,7,9]).
false.
Note that the predicate is also working with negative numbers:
?- sum_oftriple_fromlist(6,T,[-5,-3,-1,2,4,7,8,9]).
T = [-5, 2, 9] ;
T = [-5, 4, 7] ;
T = [-3, 2, 7] ;
false.
?- sum_oftriple_fromlist(-6,T,[-6,-5,-4,-3,-2,-1,2,4]).
T = [-6, -4, 4] ;
T = [-6, -2, 2] ;
T = [-5, -3, 2] ;
T = [-3, -2, -1] ;
false.
However, due to the use of is/2, the predicate only works if the first and the third arguments are ground:
?- sum_oftriple_fromlist(S,T,[1,2,3,4,5,6]).
ERROR: is/2: Arguments are not sufficiently instantiated
Exception: (7) sum_ofsub_fromlist(_G918, [_G1016, _G1019, _G1022], [1, 2, 3, 4, 5, 6]) ?
?- sum_oftriple_fromlist(6,T,[A,B,C,D,E,F]).
ERROR: is/2: Arguments are not sufficiently instantiated
Exception: (7) sum_ofsub_fromlist(6, [_G2121, _G2124, _G2127], [_G1945, _G1948, _G1951, _G1954, _G1957, _G1960]) ?
If that's fine with you, you can stop here. Alternatively, you could opt to make the predicate more versatile by using CLP(FD). Just apply these minor changes to your code:
:- use_module(library(clpfd)). % <- new
sum_oftriple_fromlist(S,T,L) :-
T=[_,_,_],
sum_ofsub_fromlist(S,T,L).
sum_ofsub_fromlist(0,[],_L).
sum_ofsub_fromlist(X,[A|Bs],[A|As]) :-
X0 #= X-A, % <- change
sum_ofsub_fromlist(X0,Bs,As).
sum_ofsub_fromlist(X,Bs,[_A|As]) :-
dif(Bs,[]),
sum_ofsub_fromlist(X,Bs,As).
Now the above queries deliver answers:
?- sum_oftriple_fromlist(S,T,[1,2,3,4,5,6]).
S = 6,
T = [1, 2, 3] ;
S = 7,
T = [1, 2, 4] ;
S = 8,
T = [1, 2, 5] ;
. % another
. % seventeen
. % results here
The second query, however, yields residual goals (see documentation for details) as results:
?- sum_oftriple_fromlist(6,T,[A,B,C,D,E,F]).
T = [A, B, C],
_G2424+A#=6,
C+B#=_G2424 ;
T = [A, B, D],
_G2424+A#=6,
D+B#=_G2424 ;
.
.
.
To get actual numbers, you have to restrict the range of the numbers and subsequently label the variables in the list:
?- L=[A,B,C,D,E,F], sum_oftriple_fromlist(6,T,L), L ins 1..6, label(L).
L = [1, 1, 4, 1, 1, 1],
A = B, B = D, D = E, E = F, F = 1,
C = 4,
T = [1, 1, 4] ;
L = [1, 1, 4, 1, 1, 2],
A = B, B = D, D = E, E = 1,
C = 4,
F = 2,
T = [1, 1, 4] ;
.
.
.
Possibly you are only interested in lists where every number only appears once:
?- L=[A,B,C,D,E,F], all_distinct(L), sum_oftriple_fromlist(6,T,L), L ins 1..6, label(L).
L = [1, 2, 3, 4, 5, 6],
A = 1,
B = 2,
C = 3,
D = 4,
E = 5,
F = 6,
T = [1, 2, 3] ;
L = [1, 2, 3, 4, 6, 5],
A = 1,
B = 2,
C = 3,
D = 4,
E = 6,
F = 5,
T = [1, 2, 3] ;
.
.
.
Or maybe you don't even want to restrict the sum:
?- L=[A,B,C,D,E,F], all_distinct(L), sum_oftriple_fromlist(S,T,L), L ins 1..6, label(L).
L = [1, 2, 3, 4, 5, 6],
A = 1,
B = 2,
C = 3,
D = 4,
E = 5,
F = S, S = 6, % sum = 6
T = [1, 2, 3] ;
.
.
.
L = [1, 2, 4, 3, 5, 6],
A = 1,
B = 2,
C = 4,
D = 3,
E = 5,
F = 6,
S = 7, % sum = 7
T = [1, 2, 4] ;
.
.
.
As you can see the CLP(FD) version of the predicate resembles a true relation as opposed to the non-CLP(FD) version. And of course your example queries yield the same answers with both versions.
Your code only considers the first 3 items in the list, and not any other combinations.
The most natural way to structure a solution involving a list is to base your recursion on the structure of the list. So:
If the first element of the list (say, X) is to be included in the 3 values that sum to N, we need to find a way to find 2 values in the rest of the list that sum to N-X.
If it isn't, just try to solve the problem using the rest of the list.
Note that you may need a "helper" version of your predicate that allows you to add other parameters. In this case, knowing how many values you need to add up would be helpful.

Next predicate confusion

I'm in the process of learning prolog, I'm currently writing a next predicate for a game which is really simple.
you have a list [1,0,1,0,0,1] A legal move is move a 1 to a zero position, the 1 can only move right to the first position containing 0, but it is allowed to jump over other values if necessary.
firstly I wrote a predicate to change the value 0 to 1:
flip_first_zero([0|Tail], [1|Tail]).
simple enough, now I'm trying to find the legal moves, I will try to explain my thought process:
next([],[],[]).
next([Head|Tail], Rest, Out):-
flip_first_zero([Head|Tail],List1),
append(Rest,List1,Out).
next([Head|Tail], [Head|Rest], List):-
next(Tail,Rest, List).
an example [1,0,0,1,1,1,0] the output should be [0,1,0,1,1,1,0] ; [1,0,0,0,1,1,1]; [1,0,0,1,0,1,1] ; [1,0,0,1,1,0,1].
[1,0,0,1,1,1,0] -> [0,1,0,1,1,1,0]
[1,0,0,1,1,1,0] -> [1,0,0,0,1,1,1]
[1,0,0,1,1,1,0] -> [1,0,0,1,0,1,1]
[1,0,0,1,1,1,0] -> [1,0,0,1,1,0,1]
So how I've understood this is, I loop through removing the head each time by conserving this in Rest so I can append it back on after.
Am I approaching this wrong?
The problem has two pieces: (1) the location of a 1, (2) the location of the first 0 after finding the 1 so that the 1 can be placed in its new position. The Prolog solution will reflect this. Your initial attempt tries to handle everything in a single predicate, which I believe makes the task a little more difficult.
The base case is easy. It represents the smallest valid move.
move([1,0], [0,1]).
Then the recursive cases. These enforce at least 3 positions in the list since the trivial case of 2 positions is already handled by the base case, and it establishes mutual exclusion in the rules to avoid redundant solutions.
% If we're at a 0 (space), keep going
move([0,X1,X2|T], [0|R]) :-
move([X1,X2|T], R).
% If we see a 1, we can move it, or we can leave it alone and move on
move([1,X1,X2|T], [0|R]) :-
place([X1,X2|T], R).
move([1,X1,X2|T], [1|R]) :-
move([X1,X2|T], R).
% Place the 1 at the first located 0 (space)
place([0|T], [1|T]).
place([1|T], [1|R]) :-
place(T, R).
So to determine valid next positions from a starting position:
| ?- move([1,0,0,1,1,1,0],R).
R = [0,1,0,1,1,1,0] ? a
R = [1,0,0,0,1,1,1]
R = [1,0,0,1,0,1,1]
R = [1,0,0,1,1,0,1]
(1 ms) no
| ?-
You can also determine what starting positions would lead to a particular next position:
| ?- move(S, [1,0,0,1,0,1,1]).
S = [1,0,0,1,1,0,1] ? a
S = [1,0,0,1,1,1,0]
S = [1,0,1,0,0,1,1]
no
This can also be done using a DCG:
move([0, 1]) --> [1, 0].
move([0|R]) --> see(0), move(R).
move([0|R]) --> see(1), place(R).
move([1|R]) --> see(1), move(R).
see(N), [X1, X2] --> [N, X1, X2].
place([1|T]) --> [0], seq(T).
place([1|R]) --> [1], place(R).
seq([]) --> [].
seq([X|Xs]) --> [X], seq(Xs).
| ?- phrase(move(R), [1,0,0,1,1,1,0]).
R = [0,1,0,1,1,1,0] ? a
R = [1,0,0,0,1,1,1]
R = [1,0,0,1,0,1,1]
R = [1,0,0,1,1,0,1]
no
| ?- phrase(move([1,0,0,1,0,1,1]), S).
S = [1,0,0,1,1,0,1] ? a
S = [1,0,0,1,1,1,0]
S = [1,0,1,0,0,1,1]
no
One logical way to approach this: find what comes before a 1, then what comes after a 1 and before a 0, and a rest. Then, you need to swap the 1 and 0 so that you have Before 1, 0, after 1 before 0, 1, after 0.
Start small. First, to just split the list whenever you have a 1, so that you have Before and After, you can use append/3 like this, using the list from your example:
?- append(Before, [1|After], [1,0,0,1,1,1,0]).
Before = [],
After = [0, 0, 1, 1, 1, 0] ;
Before = [1, 0, 0],
After = [1, 1, 0] ;
Before = [1, 0, 0, 1],
After = [1, 0] ;
Before = [1, 0, 0, 1, 1],
After = [0] ;
false.
You already get the 4 solutions you expect. Now you need to look inside After to see where to put the 1 -- well, you need to put it right after the first 0. So let's split After on a 0, but just once:
?- append(Before, [1|After], [1,0,0,1,1,1,0]),
once( append(Before0, [0|After0], After) ).
Before = Before0, Before0 = [],
After = [0, 0, 1, 1, 1, 0],
After0 = [0, 1, 1, 1, 0] ;
Before = [1, 0, 0],
After = [1, 1, 0],
Before0 = [1, 1],
After0 = [] ;
Before = [1, 0, 0, 1],
After = [1, 0],
Before0 = [1],
After0 = [] ;
Before = [1, 0, 0, 1, 1],
After = [0],
Before0 = After0, After0 = [] ;
false.
Now you have 3 pieces: one before the 1 called Before, one between the 1 and the first 0 called Before0, and a last piece after the first 0 called After0. You just need to put them back together: Before, 0, Before0, 1, After0. You can use the 2-argument append/2 that takes a list of lists in the first argument:
?- append(Before, [1|After], [1,0,0,1,1,1,0]),
once( append(Before0, [0|After0], After) ),
append([Before, [0|Before0], [1|After0]], Result).
Result = [0, 1, 0, 1, 1, 1, 0] ;
Result = [1, 0, 0, 0, 1, 1, 1] ;
Result = [1, 0, 0, 1, 0, 1, 1] ;
Result = [1, 0, 0, 1, 1, 0, 1] ;
false.
(I left only the Result bindings to save space.)
I think you are done at this point.
Thank you for all the answers, this is how I did it:
flip_first_zero([0|L],[1|L]):-!.
flip_first_zero([X|L],[X|L1]):-
flip_first_zero(L,L1).
next([1|L],[0|L1]):-
flip_first_zero(L,L1).
next([X|L],[X|L1]):-
next(L,L1).

SWI-Prolog sort predicate not working

I just made up a program, doing following task: "Get elements, which values are equal to their indexes".
Here is the code:
% get element's index
get_index([Element|_], Element, 0).
get_index([_|T], Element, Index) :-
get_index(T, Element, Index1),
Index is Index1+1.
index_equals_to_element(List, List2) :-
member(X, List),
get_index(List, X, Index),
Index =:= X,
append([], [X], List2).
It works pretty well. But there is one problem. For list [0, 3, 2, 4, 0] my predicate index_equals_to_element returns [0, 2, 0].
Okay, let it happen. But when I'm trying to output only unique elements, I'm getting the same list without any changes. Example:
?- index_equals_to_element([0, 3, 2, 4, 0], List).
% Outputs [0, 2, 0]
?- sort(List, List2).
% Outputs [0, 2, 0] either, when expected [0, 2]
It's very strange for me, because this works fine:
?- sort([0, 2, 1, 0], List).
% Outputs [0, 1, 2].
Why sort doesn't work only with the list, generated by my predicate?
A simple solution is:
index_equals_to_element(List1, List2) :-
% assume that list position index starts at 0
index_equals_to_element(List1, 0, List2).
index_equals_to_element([], _, []).
index_equals_to_element([X| Xs], Index, List2) :-
NextIndex is Index + 1,
( X == Index ->
List2 = [X| Tail],
index_equals_to_element(Xs, NextIndex, Tail)
; index_equals_to_element(Xs, NextIndex, List2)
).
Example call:
?- index_equals_to_element([0, 3, 2, 4, 0], List).
List = [0, 2].
I suggest you study it by using the trace feature of your Prolog system by typing the query:
?- trace, index_equals_to_element([0, 3, 2, 4, 0], List).
Step trough the execution until is the predicate definition is clear for you.
Your index_equals_to_element([0, 3, 2, 4, 0], List). doesn't output [0, 2, 0] as you claim, but gives three answers [0], [2] and [0]:
?- index_equals_to_element([0, 3, 2, 4, 0], List).
List = [0] ;
List = [2] ;
List = [0] ;
false.
You can use findall to get what you want:
?- findall(X, index_equals_to_element([0, 3, 2, 4, 0], [X]), List).
List = [0, 2, 0].
Update. Here is what I think a better implementation of index_equals_to_element/2:
index_equals_to_element(List, List2) :-
index_equals_to_element(List, 0, List2).
index_equals_to_element([], _, []).
index_equals_to_element([X | Rest], I, Rest2) :-
Inext is I + 1,
index_equals_to_element(Rest, Inext, NewRest),
( X =:= I ->
Rest2 = [X | NewRest]
;
Rest2 = NewRest
).
Test run:
?- index_equals_to_element([0, 3, 2, 4, 0], List).
List = [0, 2].
?- index_equals_to_element([0, 1, 2, 2, 4, 5], List).
List = [0, 1, 2, 4, 5].
The other answers are best for learning the nuts and bolts of Prolog. But here's a more concise (but also easier to grok) solution using the higher-order predicate findall/3 and nth0/3 from the SWI-Prolog library(lists):
elements_equal_to_index(List, Elements) :-
findall(Index, nth0(Index, List, Index), Elements).
Edit:
As #Paulo Moura pointed out in a comment, the above answer is only equivalent to the others offered here if all argument are instantiated. I.e., if the above encounters a free variable in the list, I will bind that variable to its index in the list instead of rejecting it as an unsatisfactory element. The addition of a test for strong equality between the index and the list element should make the answer conform:
elements_equal_to_index(List, Elements) :-
findall( Index,
( nth0(Index, List, Elem),
Elem == Index ),
Elements
).

Get list of sets where the sum of each set is X

I'm trying to figure out how to generate a list of sets, where each set has a length of N and the sum of each set is X.
I found this code:
num_split(0,[]).
num_split(N, [X | List]):-
between(1,N,X),
plus(X,Y,N),
num_split(Y,List).
And I can use that to get a list of sets with sum X:
num_split(6,List),length(List,5).
List = [1, 1, 1, 1, 2] ;
List = [1, 1, 1, 2, 1] ;
List = [1, 1, 2, 1, 1] ;
List = [1, 2, 1, 1, 1] ;
List = [2, 1, 1, 1, 1] ;
false.
The problem is that those are all permutations, and I'm looking for combinations. The output I'm looking for should be something like get_combos(Sum,Length,List):
get_combos(6,2,List).
List = [5,1];
List = [4,2];
List = [3,3];
false.
Any pointers?
If you have access to a CLP(FD) library, you can use this code:
:- [library(clpfd)].
get_combos(Sum, Length, List) :-
length(List, Length),
List ins 1 .. Sum,
% all_distinct(List), not really useful here
sum(List, #=, Sum),
chain(List, #<),
label(List).
test:
?- get_combos(10,3,L).
L = [1, 2, 7] ;
L = [1, 3, 6] ;
L = [1, 4, 5] ;
L = [2, 3, 5] ;
Maybe I misunderstood your question. Use this chain
...
chain(List, #=<),
....
to get possible duplicates values:
?- get_combos(10,3,L).
L = [1, 1, 8] ;
L = [1, 2, 7] ;
L = [1, 3, 6] ;
L = [1, 4, 5] ;
L = [2, 2, 6] ;
L = [2, 3, 5] ;
L = [2, 4, 4] ;
L = [3, 3, 4] ;
false.
Enforce an "equal or greater" restriction between successive values in the array.
You can add it on as another predicate:
is_combination([]).
is_combination([_]).
is_combination([A,B|List]) :- A =< B, is_combination([B|List]).
get_combos(Sum, Length, List) :-
num_split(Sum, Length, List),
is_combination(List).
Unfortunately, tacking it on the end of the num_split/3 does not necessarily increase its performance, so adding it directly into the algorithm would be marginally better:
get_combos(_, 0, []).
get_combos(Sum, 1, [Sum]).
get_combos(Sum, Length, [A, B|List]) :-
between(1, Sum, A),
plus(A, NextSum, Sum),
plus(1, NextLength, Length),
get_combos(NextSum, NextLength, [B|List]),
A =< B.
I'm not sure just how much more performance this gets, as the comparison has to be after the recursion, due to the less-than-or-equals operator (=<) requiring both operands to be fully instantiated for it to work.

members predicate in Prolog

I'd like to define a members predicate.
members(A, B) means that all members of the list A are members of list B.
top(N) defines how long A can be.
This is my try:
top(5).
members([X], L):-
member(X, L).
members([X| Xs], L):-
member(X, L),
members(Xs, L),
length(Xs, M),
top(N),
M < N.
I'd like to use it as follow:
members(L, [1,2,3]).
The problem with my implementation is that if I ; to get new answers, I'll finish with an ERROR: Out of local stack
?- members(I, [1,2,3]).
I = [1] ;
I = [2] ;
I = [3] ;
I = [1, 1] ;
I = [1, 2] ;
I = [1, 3] ;
I = [1, 1, 1] ;
I = [1, 1, 2] ;
I = [1, 1, 3] ;
I = [1, 1, 1, 1] ;
I = [1, 1, 1, 2] ;
I = [1, 1, 1, 3] ;
I = [1, 1, 1, 1, 1] ;
I = [1, 1, 1, 1, 2] ;
I = [1, 1, 1, 1, 3] ;
;ERROR: Out of local stack
How can I change my code to prevent this out of memory?
As already mentioned, your problem is that you do the length check after the recursive call, meaning that the recursion is unbounded. Unfortunately, just moving the length check above the recursive call like this...
members([X], L):-
member(X, L).
members([X|Xs], L):-
length(Xs, M),
top(N), M < N,
member(X, L),
members(Xs, L).
...is not so good as we get this:
L = [3, 1, 2, 3, 3] ;
L = [3, 2, 2, 3, 3] ;
L = [3, 3, 2, 3, 3] ;
L = [3, 1, 3, 3, 3] ;
L = [3, 2, 3, 3, 3] ;
L = [3, 3, 3, 3, 3] ;
ERROR: Out of global stack
While this gets us the answer, it's not that useful as it can't be put inside a larger predicate since it breaks. It breaks because we have only pushed the problem further along. Here's why:
The problem is that you are constructing the list in a top-down manner. In other words, we define the list like this: List = [Head|Tail] where we stipulate some constraints on Head and state that Tail is made up of a list of elements defined by the same constraints and bounded by a base case. This means that while we are in the middle of the recursive call, we actually only have access to Head - we cannot access the contents of Tail as it is only constructed once the interpreter has gone all the way down and reached the base case (i.e. members([X], L) :-) and then has successively added each Tail to its Head until the final List is constructed.
It may look like we have access to the length, since the length/2 call is sitting there in the middle of the recursive predicate, however since the variable being passed into length/2 for the list is at this stage not bound to anything, Prolog waits until it has finished the recursive calls beneath this point before calculating the length. The problem of course is that the length check is what is bounding the recursion, so it will just continue until it runs out of memory.
While top-down recursion tends to be the default way of constructing Prolog predicates, as this example shows, sometimes we need access to the data structure we are creating. The solution is to use bottom-up recursion. This is implemented in Prolog by means of an accumulator predicate, which starts with an empty list and proceeds to build the list up one by one, by passing the accumulator list (which is a fully ground list) through the recursive predicate. Here's how I would write an accumulator predicate for this problem:
members(I,L) :-
members_accumulator([],I,L).
members_accumulator(Tail,I,L) :-
length(Tail, M),
top(N),
M < N,
member(X, L),
members_accumulator([X|Tail],I,L).
members_accumulator(I,I,_).
We need two predicates, as the first is a wrapper around the accumulator which passes the empty list to the accumulator predicate. The base case no longer has anything to do with the empty list - all it has to do is state that the final accumulator list is actually the final list that we're after (which has been threaded through the accumulator predicate just for this purpose). Also, in this case, the accumulator predicates need to be in this order otherwise there will be one choice point that evaluates as false right at the end.
Getting ones head around recursion in Prolog and when you need to use bottom-up recursion rather than top-down is a non-trivial feat. I didn't really have a solid grasp on it at all until I had a good read through The Art of Prolog. There should also be plenty of info about accumulators online.
Here is an alternate implementation which does'nt require calculating the length of the list. Here N is the length of list A. This solution gives all the answers without going out of stack.
members([X],L,1) :- member(X,L).
members([H|T],L,N) :- N>1 , member(H,L) , N1 is N-1, members(T,L,N1).
Example execution:
?- members(L,[1,2,3],5).
L = [1, 1, 1, 1, 1] ;
L = [1, 1, 1, 1, 2] ;
L = [1, 1, 1, 1, 3] ;
L = [1, 1, 1, 2, 1] ;
...
L = [3, 3, 3, 1, 2] ;
L = [3, 3, 3, 3, 1] ;
L = [3, 3, 3, 3, 2] ;
L = [3, 3, 3, 3, 3] ;
No
You do the check for the depth after the recursion. So the depth of the recursion is not limited, only the resulting lists are discarded as too long.
Use meta-predicate maplist/2,
lambdas, and membership predicate memberd/2 and simply write:
:- use_module(library(lambda)).
members(As,Bs,N) :-
length(Xs,N),
append(As,_,Xs),
maplist(Bs+\A^memberd(A,Bs), As).
Sample query with abbreviated answer sequence:
?- members(As,[1,2,3],5).
As = [ ] ;
As = [ 1] ; As = [ 2] ; As = [ 3] ;
As = [ 1,1] ; As = [ 1,2] ; /* ... */ As = [ 3,3] ;
As = [ 1,1,1] ; As = [ 1,1,2] ; /* ... */ As = [ 3,3,3] ;
As = [ 1,1,1,1] ; As = [ 1,1,1,2] ; /* ... */ As = [ 3,3,3,3] ;
As = [1,1,1,1,1] ; As = [1,1,1,1,2] ; /* ... */ As = [3,3,3,3,3] ;
false.
Above query universally terminates.
Let's look at the size of the solution set:
?- setof(As,members(As,[1,2,3],5),Ass), length(Ass,N_Solutions).
Ass = [[],[1],[1,1],[1,1,1],[1,1,1|...],[1,1|...],[1|...],[...|...]|...],
N_Solutions = 364.
?- 364 =:= 1 + 3 + 3^2 + 3^3 + 3^4 + 3^5.
true.

Resources