Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prolog - check if list is empty []

Tags:

list

prolog

I am just trying to figure out how to check if a list is empty, I put together something that checks the length of the list, and additionally should check to see if the list isn't empty.

% Gives the length of a list.
listlength([]     , 0 ).
listlength([_|Xs] , L ):- 
    listlength(Xs,N), 
    L is N+1. 

% checks to see that the length of the list is greater than or equal to 3 and not empty.
check_length( [] ).
check_length( L  ):-
    listlength(L, Len),
    Len >= 3,
    L \== [].    %This is the bit of code I'm having problems with 
                  it should be false if the list is just [] or empty.

I am a student so I don't necessarily need a straight answer I'm just trying to figure out what I'm doing wrong.

like image 915
Jarrod Lofy Avatar asked Nov 13 '15 00:11

Jarrod Lofy


People also ask

How do I check if a list is empty in Prolog?

is_empty(List):- not(member(_,List)). Which checks if the given list has any members, and returns the negation of that. [] => No members, is empty.

How do you check if an item is in a list Prolog?

If you want to check if a list contains a member, use memberchk/2 . so memberchk(I/J, Item) succeeds if I/J is in the list Item . Your include/3 predicate has no base case, and attempt to ensure that every element of the given list is I/J , so it will always fail.

How do you create a blank list in Prolog?

An easy way to create a list of a given length consisting of the same element, or just empty lists in this case, is to use maplist2 : generate_board(Length, Board) :- length(Board, Length), maplist(=([]), Board).

How do you find the length of a list in Prolog?

Length Calculation If the list is not empty, then L = [Head|Tail], then its length is 1 + length of Tail.


2 Answers

You don't need to explicitly test for L being an empty list; it having a length > 0 establishes that.

And you already know how to test for a list not being empty, since you used it in listLength: L=[_|_] (that is, L is a list with at least 1 element).

like image 86
Scott Hunter Avatar answered Oct 01 '22 10:10

Scott Hunter


The question is "how to check if a list is empty". By definition, an empty list is a list with no elements, i.e., the [] list. You could simply check if your list unifies with that.

like image 31
madanasta Avatar answered Oct 01 '22 09:10

madanasta