Eigenvalue
Eigenvalue

Reputation: 1133

Telling if a list is the size of 1 in Prolog

I'm pretty new to prolog and I'm trying to write a predicate such that I can tell if a list is the list of size one or not. Currently I have this:

one([H | T]) :- H \= [] ,T == [].

There is problems with this, at least my logic is that if the H is not empty and the tail has nothing, then it must be the case that there is something in the head and thus has a size of one. Else it does not.

Some insight on solving this problem would be much appreciated thank you.

Upvotes: 1

Views: 453

Answers (2)

Nicholas Carey
Nicholas Carey

Reputation: 74325

You could try the built-in length/2:

is_list_of_length_one( Xs ) :- length(Xs,1).

Or you could simply say

is_list_of_length_one( Xs ) :- nonvar(Xs) , Xs = [_] .

Upvotes: 1

Sergii Dymchenko
Sergii Dymchenko

Reputation: 7229

This is easy, just one fact:

one([_]).

Upvotes: 5

Related Questions