I want to count how many g items appear in a list, below is the code I was trying now, but I got false when return.
g(E) :- memberchk(E, [apple, orange, pear, grape, lycee, pineapple,dragonfruit]).
countFruit([], No):- write(' >> No of Fruits : '), write(No), nl.
countFruit([H|T], No) :- not(g(H)), countFruit(T,No).
countFruit([H|T], No) :- No1 is No+1, countFruit(T,No1).
?countFruit(H,0). (H is a list).
By calling
?- countFruit(H,0).you are telling prolog to unify theNovariable in yourcountfruit\2predicate to0. So the result can only ever be0orfail.If I run your code as-is though, I get the following:
Here’s my take on this problem: