1

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.

false
  • 10,264
  • 13
  • 101
  • 209
jc2000
  • 13
  • 2
  • 3
    Please put your code into your post. You can easily do that by using the "Code Sample" button in the editor – Fabian Bettag Feb 06 '20 at 12:54
  • 3
    If you wonder why @false's solution works and yours not, have a look at the line `x is H-1` and check what the difference between lower case and upper case names is. – lambda.xy.x Feb 06 '20 at 14:16

1 Answers1

3
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.

false
  • 10,264
  • 13
  • 101
  • 209