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.
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.
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.
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).
Length Calculation If the list is not empty, then L = [Head|Tail], then its length is 1 + length of Tail.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With