Haise Sasaki
Haise Sasaki

Reputation: 329

Check if all items in a list are a specific number in Prolog

I'm learning prolog. I'm trying to write a small program that checks if all entries in a given list are 1.

singleton([Head|Tail]) :- 
    Head = 1,
    singleton(Tail).

The program returns false when I pass the list [1,1]. Why?

Upvotes: 1

Views: 158

Answers (2)

Reema Q Khan
Reema Q Khan

Reputation: 878

A slight correction to your code:

singleton([]).
singleton([Head|Tail]) :- 
Head = 1,
singleton(Tail).

trace, (singleton([1,1,1])).
 Call:singleton([1, 1, 1])
 Call:1=1
 Exit:1=1
 Call:singleton([1, 1])
 Call:1=1
 Exit:1=1
 Call:singleton([1])
 Call:1=1
 Exit:1=1
 Call:singleton([])
 Exit:singleton([])
 Exit:singleton([1])
 Exit:singleton([1, 1])
 Exit:singleton([1, 1, 1])
1true

Upvotes: 0

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476614

You did not define that the empty list satisfies singleton/1 as well. If you call singleton([1, 1]). then the recursion will call singleton([1]) and when processing that, it will call singleton([]). Since singleton([]) fails, this thus means that singleton([1]) will fail, and therefore singleton([1,1]).

You thus can use:

singleton([]).
singleton([1|Tail]) :- 
    singleton(Tail).

Upvotes: 2

Related Questions