2

I have been given a question in my assignment that asks to write a Prolog program that takes as input a list of numbers and succeeds if the list contains only 0s.

I am having trouble on how to make the program search for zeroes. For example, a query like:

?- zero([0,0,0,0]).

Should give us true and it should return false whenever there's a number other than zero in it.

Paulo Moura
  • 18,373
  • 3
  • 23
  • 33
Bob
  • 35
  • 6

2 Answers2

1

why are you asking us to do your homework for you? anyway, it's very simple recursion. something like:

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

just keep peeling of zero's until your list is empty. it isn't so hard ;)

Jumboman
  • 521
  • 3
  • 9
1

Usually, one would not define a proper predicate for this, but rather use maplist/2 for the purpose:

..., maplist(=(0), Zs), ...

To give a concrete example:

?- Zs =[A,B,C], maplist(=(0), Zs).

This query corresponds to:

?- Zs = [A,B,C], call(=(0), A), call(=(0), B), call(=(0), C).

or even simpler:

?- Zs = [A,B,C], 0 = A, 0 = B, 0 = C.

If you want to define this as a separate predicate, remember to use a good name for it. Each element of the list is a zero, and the relation describes the entire list of such zeros. The convention for lists in this case is to use the plural word. Thus zeros/1:

zeros([]).
zeros([0|Zs]) :-
   zeros(Zs).
Community
  • 1
  • 1
false
  • 10,264
  • 13
  • 101
  • 209