Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the number of elements greater than a number in a list in PROLOG

Tags:

prolog

Hello and thank you for taking the time to read this question. I have the following problem:

Given a list that returned the number of numbers greater than X Example:

greater (4, [1,2,3,4,5,6], N) Result. N = 2 My code is:

greater(0,[],0):-!, fail.
greater(N,[N],1).
greater(N,[H|Q],X):-H>N,greater(Q,N,X),X is X+1.

The problem is that PROLOG only returns False but not the value of X.

I hope you can explain to me what I am doing wrong, I thank you in advance for your

like image 359
Krasnax Avatar asked Dec 31 '25 22:12

Krasnax


1 Answers

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?

like image 85
lurker Avatar answered Jan 06 '26 20:01

lurker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!