I assume that you are required to do this using ECLiPse declarative loops, but just in case: are you aware about intersection/3
already implemented in ECLiPSe?
[eclipse]: intersection([1, 2, 3], [2, 3, 4], X).
X = [2, 3]
Yes (0.00s cpu)
And here is one of many ways to do it with loops:
setIntersection(Xs, Ys, Zs) :-
( foreach(Xi, Xs), fromto([], ZsPrev, ZsCurr, Zs), param(Ys) do
( memberchk(Xi, Ys) ->
ZsCurr = [Xi | ZsPrev]
;
ZsCurr = ZsPrev
)
).
Test run:
[eclipse]: setIntersection([1,2,3], [2,3,4], X).
X = [3, 2]
Yes (0.00s cpu)
Elements are in reversed order compared to what you gave in example, but with sets it should not matter. You can reverse or sort elements in the end, if you want.
BTW, why is "Perl" in the header of the question?