0
votes

I want a predicate that goes through a list of lists and checks if each of those lists verify certain conditions, in case a list verifies the conditions, it gets added to ResultList (another list of lists). I wrote this:

mypredicate(ListOfLists, ReferenceList, ResultList) :-
    mypredicate(ListOfLists, ReferenceList, ResultList, []),

mypredicate([H|T], ReferenceList, ResultList, Acc) :-
    elementos_comuns(ReferenceList, H),
    H \== ReferenceList,
    append(Acc, H, ResultList),
    T \== [],
    mypredicate(T, ReferenceList, ResultList, ResultList).

I only want to append if both lines above "append" return true, and regardless of what happens in the first 3 lines, I want it to run the last line if T \== [].

The problem is that when it reaches an element of ListOfLists that doesn't verify one these two:

elementos_comuns(ReferenceList, H),
H \== ReferenceList,

the whole thing returns false.

I need ResultList to be a list of lists that contains the lists from "ListOfList" that verify

elementos_comuns(ReferenceList, H),
H \== ReferenceList,

I have no idea how to do this, any help is appreciated.

1

1 Answers

0
votes

Imagine you call mypredicate with some list [A, B, C]. It will check some conditions on A, then recurse with [B, C]. It will check some conditions on B, then recurse with [C]. It will check some conditions on C, but then, since T is now [], it will fail at T \== []. Your predicate has no chance of succeeding while you have this condition. You should probably remove it, and add another clause of the form mypredicate([], ..., ..., ...).

Even then your predicate will only be able to handle cases where all the conditions are satisfied. It will fail as soon as you run it on a list where elementos_comuns/2 fails.

There are three distinct situations you want to handle:

  • empty list
  • list [H | T] where H satisfies the elementos_comuns/2 check
  • list [H | T] where H does not satisfy the elementos_comuns/2 check

A predicate that wants to handle three distinct cases should usually consist of three clauses.