Reputation: 13
I have a list called X and I am trying to iterate through the list, I have a separate list Y where the elements of Y are (U,V) where U is X+1 and V is X-1. I have been trying to append U and V to Y with no success. SO it should work such that if X is [4,5,6] Y will be [(3,5),(4,6),(5,7)]
/**
list_looping([], _).
list_looping([H|T],A) :-
x is H-1,
x is H+1,
append([(x,y),T],A).
pairs([],[]).
pairs([H|T],[(U,V),L]):-
list_looping([H|T],[(U,V),L]).
*/
pairs(X,Y) :-
forall(member(X,[1,2,3]),((U is X+1,V is X-1),writeln((U,V)))).
I have tried two different implementations, in the first I am trying to recursively search through the list, with little success. In the second I am trying to use Prolog's inbuilt forall function, this obviously doesn't work either.
Upvotes: 1
Views: 67
Reputation: 10102
list_pairs([], []).
list_pairs([X|Xs], [(U,V)|UVs]) :-
U is X-1,
V is X+1,
list_pairs(Xs, UVs).
or more compactly
list_pairs2(Xs, UVs) :-
maplist(e_pair, Xs, UVs).
e_pair(X, (U,V)) :-
U is X-1,
V is X+1.
and most compactly using library(lambda)
for
SICStus|SWI
list_pairs3(Xs, UVs) :-
maplist(\X^(U,V)^( U is X-1, V is X+1 ), Xs, UVs).
Most frequently, one does not even name these predicates but uses the maplist
-goal directly.
Upvotes: 3