user-2147482428
user-2147482428

Reputation: 167

Recursively checking if all elements in a list are a certain value in Prolog

I have defined it as follows in Prolog:

listOfa([H|T]):- H = 'a', listOfa(T).
listOfa([]).

It does what I want it to do. It checks if all items in a list are a certain element, in this case the character a, and returns true or false accordingly. However, it returns true if the list is empty, and I don't want it to. Except, I'm not sure what to use as a base case for the recursion besides the empty list. How do I maintain the recursion without it returning true for an empty list?

Upvotes: 3

Views: 228

Answers (1)

mat
mat

Reputation: 40768

It is natural to start with two clauses for empty and non-empty lists, and in fact you can keep this pattern! You can easily solve this with a separate predicate that is true iff its argument is a list with at least one element.

For example:

not_empty([_|_]).

Then, post the conjunction of this predicate and that which you have already successfully implemented.

If you want, you can also combine this into a third predicate that consists only of this conjunction.

Also, check this out:

?- maplist(=(a), Ls).

After combining these goals, you can—by purely algebraic resoning—find an even shorter solution!

Upvotes: 3

Related Questions