2

I'm having an issue in Prolog. I can only use recursive programming in logical purity (university rules).

I want to check if each list of a list of lists have, at least, one element inside. For example:

[[0], [0], [0, s(0), 0], [s(0)]] -> valid

[[0], [], [0, s(0), 0], [s(0)]] -> not valid (because of the [])

So I check it this way:

% Auxiliar Method 1

isList([]).
isList([_|Tail]) :-
    isList(Tail).

% Auxiliar Method 2

listLength([], 0).
listLength([_|Tail], NumberOfElements) :-
    listLength(Tail, NumberOfElementsRecursive), 
    NumberOfElements = s(NumberOfElementsRecursive).

% Auxiliar Method 3

moreThan(s(X), 0).
moreThan(s(X), s(Y)) :-
    moreThan(X, Y).

% Real Method

listOfListOfListsNotEmpty([Head|Tail]) :-
    isList(Head),
    listLength(Head, N),
    moreThan(N, 0),
    listOfListOfListsNotEmpty(Tail).

My issue is the last iteration. For example, if I want to check this:

listOfListOfListsNotEmpty([[0], [0]]).

The iterations are this way:

Iteration 1:
    Head: [0]
    Tail: [0], []

    [0] has at least one element? yes

Iteration 2:
    Head: [0]
    Tail: []

    [0] has at least one element? yes

Iteration 3:
    Head: []
    Tail: 

    [] has at least one element? no

How can I ignore that last check of an empty list??

false
  • 10,264
  • 13
  • 101
  • 209
sanz_sual
  • 53
  • 5

2 Answers2

3
lls_nonempty([]).
lls_nonempty([[_|_]|Ess) :-
   lls_nonempty(Ess).
false
  • 10,264
  • 13
  • 101
  • 209
2

"For all list elements some predicate P holds" is commonly expressed by using maplist/2. So there's no need to define an extra predicate of your own here!

Sample queries:

?- maplist(dif([]), [[0],[0],[0,s(0),0],[s(0)]]).
true.

?- maplist(dif([]), [[0],[],[0,s(0),0],[s(0)]]).
false.
repeat
  • 18,496
  • 4
  • 54
  • 166