Reputation: 45
I have to find all Indexes of a given Element in a List and return it as a list. So for example:
?- indexList(a,[a,b,c,a,b],Rs).
Rs = [0,3]
My Idea is:
positions( E, L, P ) :- positions( E, L, 0, Rs ).
positions( E, [], _, [] ).
positions( E, [E|Xs], P, [P|PT] ) :- P1 is P + 1, positions( E, Xs, P1, PT ).
positions( E, [X|Xs], P, PT ) :- P1 is P+1, positions( E, Xs, P1, PT ).
When I trace this I get a List in which every Position is in (in the step before the last step). But in the last steps he somehow changes it and returns just true.
Upvotes: 2
Views: 255
Reputation: 22585
Your problem is that instead of using Rs
to return the list of positions you are using P
.
You should have seen a lint warning (singleton variables P and Rs) in positions/3
that should have warned you of this.
Also, in the third clause of positions/4
you should check that E is different than X:
positions( E, L, Rs ) :- positions( E, L, 0, Rs ).
positions( E, [], _, [] ).
positions( E, [E|Xs], P, [P|PT] ) :- P1 is P + 1, positions( E, Xs, P1, PT ).
positions( E, [X|Xs], P, PT ) :- E\=X, P1 is P+1, positions( E, Xs, P1, PT ).
Upvotes: 2
Reputation: 149
You made a small mistake in the first line. You are invoking positions(E, L, 0, Rs)
, but the last parameter should be P
, in order to make a binding with the last parameter with the same name from the head of the clause. So the first line should look like this:
positions(E, L, P) :- positions(E, L, 0, P).
Upvotes: 2