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

0

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

may(0,[],0):-!, fail.
may(N,[N],1).
may(N,[H|Q],X):-H>N,may(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 help.

    
asked by Krasnax 21.10.2018 в 22:46
source

1 answer

0

First error when you call may (Q, N, X) in the rule of the third line, then you are trying to step X with X is X + 1. This assignment in Prolog is not allowed since "Variables" can not be modified with values already assigned. Second it returns false because when may (N, [H | Q], X): - H > N, may (Q, N, X), X is X + 1. compare 1> 4 false and since you can not enter the other rules (since one is with an empty list and the other if it only has one elemneto) it pulls false and the backtracking returns false. In prolog what is used and for me it is very useful to understand the operation is to write trace. at the prompt to see how the program is running and with nodebug. the trace mode is exited. Your program would be the following:

mayor(_,[],0).
mayor(N,[H|Q],X):- H>N, mayor(N,Q,X1), X is X1+1.
mayor(N,[H|Q],X):- H=< N, mayor(N,Q,X).

The use of the underscore is so that it is not the Singleton warning. Its function is another, but not to entangle you just tell you the above, as you will see I create a variable X1 in the second line to save the amount of values that fulfilled the condition of older, and then in the bottom I call when they are less than N because otherwise, when he is just with a minor he will start the backtracking and cut the recursion, throwing false.  I hope you understand and anything you answer me.

    
answered by 22.10.2018 / 01:01
source