Determining if a list is empty or not

15,813

Solution 1

I know it's old thread but still this might be useful for those using SWI-Prolog. Instead of defining their own rules, you can try:

nth0(0, List, _).

It is used to return the first element on the list, which in case of empty list simply fails.

Solution 2

Since you are only dealing with lists of the form [H|T] your clauses will only match for lists that have at least one list element. In other words, you get the answer false for the empty list because there is not a matching clause - not because the length is 0.

Share:
15,813
zihaow
Author by

zihaow

I am a developer as well as a photographer.

Updated on June 04, 2022

Comments

  • zihaow
    zihaow almost 2 years

    I want to do some if | else stuff in prolog. Below is my code, Prolog will return 'R = false' if my input list is not empty, it will return 'false' if my list is empty. What do I miss?

    Code:

    isEmpty([H|T],R) :- 
        length([H|T],L),
        ( L > 0 -> R = 'false'
        ;
        L =:= 0 -> R = 'true'
        ).
    

    Prolog Output:

    1 ?- isEmpty([],R).
    false.
    
    2 ?- isEmpty([1],R).
    R = false.
    
    3 ?- isEmpty([1,2,3],R).
    R = false.