Write a Prolog function countAllX which counts the number of
Write a Prolog function countAllX which counts the number of occurrences of an element in a list, no matter how deeply nested they are. For example:
countAllX (A, [A B A [A 1 A [A A]]], N)
Returns N = 6
Thanks a lot for your help!!!
Solution
countAllX([],x,0).
countAllX([x|T],x,y):-countAllX(T,x,z),y is 1+z;
countAllX([x1|T],x,z):-x1\\=x,countAllX(T,x,z). // here we are creating a new dummy variable called X1 that counts the number of occurences of a particular element
countall(LIST,x,c):-
sort(LIST,LIST1) , // this helps in sorting out the elements and helps in counting the number of occurances of a particular number even if it is repeated
member(x,LIST1),
count(LIST,x,c).

