HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Implementing a zipwithindex predicate in prolog

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
implementingzipwithindexprologpredicate

Problem

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?

Solution

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

Code Snippets

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

Context

StackExchange Code Review Q#49527, answer score: 4

Revisions (0)

No revisions yet.