4
\$\begingroup\$

I want to implement a predicate of the form:

zipwithindex(?List1, ?List2)

which is true when the elements of List2 are the same as in List1 but are paired with the index of the element.

This is what I have:

zipwithindex([],I,S,S).
zipwithindex([H|T],I,S0,S):-
 append(S0,[H/I],S1),
 I1 is I+1,
 zipwithindex(T,I1,S1,S).
zipwithindex(List1,List2):-
 zipwithindex(List1,0,[],List2).

Is there a better way to implement this?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked May 10, 2014 at 20:44
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

sure:

zipwithindex(List1, List2) :-
 findall(E/I, nth0(I, List1, E), List2).

Edit - after Tudor' comment

bagof/3 it's much better than findall/3, as it doesn't introduce unwanted new variables. This can be of utmost importance when working with constrained variables - i.e. CLP(FD) or CHR

answered May 10, 2014 at 20:50
\$\endgroup\$
1
  • 3
    \$\begingroup\$ I would suggest bagof/3 instead of findall/3 in this case as, if there are unbound variables in List1, List2 will have new variables instead of the original ones. E.g. ?- zipwithindex([X,Y,Z],L2). will produce L2 = [_G41/0, _G35/1, _G29/2]. \$\endgroup\$ Commented Jun 9, 2014 at 7:46

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.