1
votes

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.

2
Your answer works! What is the problem with it? It is a bit more complicated than necessary, but it is also very declarative in nature and makes the meaning of your predicate rather clear. It's true, however, that @Sergey Dymchenko's answer is cleaner.Shon
@aBathologist OP's answer doesn't always work. For example, [A] is a list of size 1, and length([A], L). will give 'L = 1', but OP's code fails on one([A]). The reason is that it fails on one([[]]). Correct code could be just one([H | T]) :- T==[]., but of course that's equal to one([_]).Sergii Dymchenko
@SergeyDymchenko Thanks! I had overlooked [[]].Shon

2 Answers

5
votes

This is easy, just one fact:

one([_]).
1
votes

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 = [_] .