Since a predicate call fails in Prolog if there are no success paths for that call, then the following predicate clause serves no purpose. You can remove it.
greater(0,[],0):-!, fail.
Your next clause is your recursive base case and is incorrectly formulated:
greater(N,[N],1).
This succeeds even though it violates your condition that you want to count elements in the list that are greater than N
. N
is not greater than N
. What should this clause look like if you want greater(N, [X], 1).
to succeed?
In your recursive clause, you have a problem:
greater(N,[H|Q],X):-H>N,greater(Q,N,X),X is X+1.
X is X+1
will always fail because the value of X
cannot possibly ever be the same as the value X+1
. That is, there is no number that is equal to itself plus one. You need to use an auxiliary variable:
greater(N,[H|Q],X):-H>N,greater(Q,N,X1),X is X1+1.
Finally, you're missing the case when H =< N
:
greater(N,[H|Q],X):-H=<N, ....
What should this clause look like?
X is X+1
is non-sensical. A variable can only be unified with one value, and a variable thus can not be1
and2
at the same time. – Willem Van Onsemfail
in the first clause? Furthermor what should happen ifH <= N
here? – Willem Van Onsemgreater(0,[],0):-!, fail.
.greater(0, [], 0)
will fail if it doesn't succeed via your other predicate clauses. Your base case,greater(N,[N],1).
is not correct. This says thatN
is greater thanN
, which certainly isn't true. What should the base case be? What is the case where you have a single element list and a number? When should it succeed with 1? – lurker