Reputation: 23
Hello i can't figure out how to solve an assignment. I am supposed to find the consecutive element combinations from a list. For example: the list [1,2,3] should give me [1],[2],[3], [1,2], [2,3], [1,2,3] but the problem i have is that my attempt also gives me [1,3]
Code:
subseq([], []).
subseq([H|T], [H|R]) :- subseq(T, R).
subseq([_|T], R) :- subseq(T, R).
Upvotes: 2
Views: 581
Reputation: 476544
The problem here is that on each element of the given list, you have two clauses:
So that means you generate all lists where for every item it is an option to include it, or exclude it.
For a subsequence, the ones defined in your question, it is a different story: you basically have two selection points:
Stopping a subsequence is actually the same as generating a prefix:
myprefix(_, []).
myprefix([H|T], [H|T2]) :-
myprefix(T, T2).
So now for a subsequence, we only need to branch over the starting point, and then add a prefix of the remaining list, like:
subsequence([H|T], [H|T2]) :-
myprefix(T, T2).
subsequence([_|T], T2) :-
subsequence(T, T2).
This then yields the expected:
?- subsequence([1, 2, 3], X).
X = [1] ;
X = [1, 2] ;
X = [1, 2, 3] ;
X = [2] ;
X = [2, 3] ;
X = [3] ;
false.
Upvotes: 1