Reputation: 23
How could I achieve something similar to the nth0/3
predicate on a list of lists ?
I would like to be able to tell what is the index of an element in a list of lists but only interested in the inner list index. What I mean is lets say I have the following predicate indexOf([[a,b,c], [d,e,f], [g,h]], d, Index)
and it returns Index=0
because d is the first element of the inner list.
indexOf([[a,b,c], [d,e,f], [g,h]], c, Index)
should return Index=2
since it is the 3rd element of the inner list.
What I have done so far is the following:
iterateOuter([]).
iterateOuter([[H|T]|LIST], Elem,Idx):-indexOf([H|T],Elem, Idx2),(Idx is Idx2;iterateOuter(LIST, Elem,Idx)).
indexOf([_|Tail], Element, Index):-indexOf(Tail, Element, Index1), Index is Index1+1.
indexOf([Element|_], Element, 0).
if I invoke iterateOuter([[a,b,c],[r,t,o]],c,Ind).
It will give me Ind = 2
and that's fine but if I say:
iterateOuter([[a,b,c],[r,t,o]],r,Ind).
it will simply give me false since it is only giving results on the first inner list.
Upvotes: 2
Views: 128
Reputation: 10122
If you have nth0/3
already, you have all you need:
?- Xss = [[a,b,c],[r,t,o]], nth0(I, Xss, Xs), nth0(J, Xs, c).
Xss = ["abc","rto"], I = 0, Xs = "abc", J = 2
; false.
?- Xss = [[a,b,c],[r,t,o]], nth0(I, Xss, Xs), nth0(J, Xs, r).
Xss = ["abc","rto"], I = 1, Xs = "rto", J = 0
; false.
Upvotes: 1
Reputation: 4098
Since you're only interested in the index of the inner list, you can just use member/2
instead of nth0/3
to get the sublist, as False suggested. Each sublist is a member of the list Ls, so you only need to find if E is the nth element of a member:
nth_of_a_sublist(N, Ls, E) :-
member(L, Ls),
nth0(N, L, E).
To check for the nth_of_a_sublist on all lists, you can use findall/3
.
But False's solution is nicer, I think, because it gives you the index of the list that contains the element, which you can ignore if you don't need it.
Upvotes: 1