Question

So before I start, here is the problem:

I have an example List Xs = [1,2,3] and List Ys = [2,3,4]. The two common elemental members from these two lists are [2,3]. So I'm trying to create a predicate setIntersection(Xs, Ys, Zs), where the resulting list ( [2,3] ), will be bound to Zs, and I'm trying to do this using the Prolog language that can run on the ECLiPSe program on Windows and it must be using the loop iterators, NO RECURSION.

Here's the code that I have so far:

setIntersection(Xs, Ys, Zs) :-
    ( foreach(Alpha, Xs), fromto([Ys], [Head|Tail], Tail, []), foreach(Bravo, Ys)
        do
             ( (Alpha =:= Head)
                   -> Bravo = Head;
                   fail
             )
    ).

Another version of the code I have is this:

setIntersection(Xs, Ys, Zs) :-
    ( foreach(Alpha, Xs), param(Ys, Zs)
        do
             ( foreach(Bravo, Ys), foreach(Charlie, Zs), param(Alpha)
                   do
                         ( ( Alpha =:= Bravo)
                            -> Charlie is Alpha;
                            !
                         )
             )
    ).

THE RESULT (from the second code):

?- setIntersection([1,2,3], [2,3,4], X).
X = [2, 3, _412]
Yes (0.00s cpu)

The results I get is very strange for the code above.

Please help me out with this problem, I would be very grateful. Thank you!

Was it helpful?

Solution

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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top