Question

Background

I need to write a relation power(P) that looks through a list and decides if all but one element of P is zero.

Here is what I have:

%I have a relation called zero(P) which decides if every element is zero.

power([H|T]) :- H is not zero,  %The current element is non zero, the tail is all zero.
                zero(T).         
power([0|T]) :- power(T).       %The current element is zero, 
                                %but the tail has a non zero element in it.

Some resources suggest using the cut operator (!), which controls backtracking and I don't think that is what I'm looking for.

I have also come across the not provable operator (\+), which seems to swap the result (is not provable returns yes), and I don't think that's what I want either.

I did find the Prolog Dictionary, but I can't figure out what "not" means or how to use it (as you can imagine, Ctrl+F finds many instances of " not ").

Question

How can I say 'H is not zero' in prolog?

EDIT The list is a list of integers.

Was it helpful?

Solution

Assuming your argument is a list of numbers, you can simply use arithmetic operators:

power([H|T]):- H =\= 0, zero(T).
power([H|T]):- H =:= 0, power(T).

In general, you could also write \+ (H=0). That means, H can not be unified with 0.

The question is, what do you want to happen if this predicate is called with a list that is not a list of numbers. The above code would cause an error. If you want it to just fail in such cases, then it can be defined as

power([H|T]):- \+(H=0), zero(T).
power([H|T]):- H=0, power(T).

OTHER TIPS

A working solution using 'not provable' operator:

  zero([]).
  zero([0|T]) :- zero(T).

  power([H|T]) :- \+ zero(H), zero(T).         
  power([0|T]) :- power(T).

zero/1 seems a rather specialized predicate. If you want to learn about more idiomatic (advanced?) Prolog, consider a 'one liner' definition, based on library(apply):

power(L) :- include(=\=(0), L, [_]).

test:

?- power([0,99,0,0]).
true.

?- power([0,99,0,1]).
false.

Of course, I can't imagine why you named such predicate 'power'...

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