0
votes

I am struggling to understand why findall/3 behaves as such in my program. Basically I have wrote I predicate , that is supposed to take a list , and return each possible couple of indexes for instance if my list has length 3, pairs([1,2,3],L) will return [1/2, 1/3, 2/3] which is a list as I expected.( inside my pairs predicate i generate this list L with findall )
But I have wrote another predicate, that's supposed to return me a list with all the sublists , of a list and the predicate also uses findall, but the result is not what I expected.

/*calculate a list CASES with all the sublists from LIST .*/
test(LIST, CASES):-
   pairs(LIST, L),
   member(X/Y, L),  
   findall(SUBLIST, sublist(LIST, X, Y,  SUBLIST), CASES).

and the result is something like that (I had to press ; to generate all results).

[[1, 2]]    
[[1, 2, 3]] 
[[2, 3]]

why results from findall do not come with a list?

1
member(X/Y, L) has three solutions in your case... - false
I got it you mean, that I have wrote, for each member findall .. but for each member (couple of indexes) there is only one sublist. - brucebanner
is there a way to put all the sublists, in a LIST with a builtin predicate or I should use some form of append? - brucebanner

1 Answers

1
votes

When findall(SUBLIST, sublist(LIST, X, Y, SUBLIST), CASES) is evaluated X and Y are already bound to values. For sublist([1, 2, 3], 1, 2, SUBLIST), there is exactly one solution ([1, 2]), which findall returns in a list.

When you backtrack, X and Y get assigned different values and findall is evaluated again, leading to a different single result.

You have to move the member call inside the findall

test(LIST, CASES):-
   pairs(LIST, L), 
   findall(SUBLIST, (member(X/Y, L), sublist(LIST, X, Y,  SUBLIST)), CASES).

(I'm not entirely sure about the syntax anymore, but it was something like this)