Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numbers in a list smaller than a given number

Tags:

xMenores(_,[],[]). xMenores(X,[H|T],[R|Z]) :-    xMenores(X,T,Z),    X > H,    R is H. 

xMenores takes three parameters:

  • The first one is a number.
  • The second is a list of numbers.
  • The third is a list and is the variable that will contain the result.

The objective of the rule xMenores is obtain a list with the numbers of the list (Second parameter) that are smaller than the value on the first parameter. For example:

?- xMenores(3,[1,2,3],X). X = [1,2].                        % expected result 

The problem is that xMenores returns false when X > H is false and my programming skills are almost null at prolog. So:

?- xMenores(4,[1,2,3],X). X = [1,2,3].                      % Perfect.  ?- xMenores(2,[1,2,3],X). false.                            % Wrong! "X = [1]" would be perfect. 

I consider X > H, R is H. because I need that whenever X is bigger than H, R takes the value of H. But I don't know a control structure like an if or something in Prolog to handle this.

Please, any solution? Thanks.