Home > Net >  Union of list of lists in prolog?
Union of list of lists in prolog?

Time:07-26

How is it possible to get the following (swi-)prolog predicate:

union( ListOfLists, -ResultList)

in the form:

ListOfLists = [A1, A2, A3, ..., An]

ResultList = A1 ∪ A2 ∪ A3 ∪ ... ∪ An 

CodePudding user response:

If your "union" is commutative and if the identity element is the empty set, you could trivially define:

union(Ls, U, Op, Empty) :-
    foldl(Op, Ls, Empty, U).

How do you represent your union? If it is a list, then [] is the empty set, and if you already have a union/3 defined (where the last argument is the union of the first two), then:

union(Ls, U) :-
    foldl(union, Ls, [], U).

But what is the computational complexity of your union/3?

  • Related