Search code examples
prolog

How to correct this 'Greater Than' Arithmetic Prolog code?


I am trying to write a simple prolog program where a number is compared with the elements in a list. To check that the number is greater than which elements in the list, and it simply returns the list with the elements that are less than the number. Example: gt(12,[19,4,6,22],L), this should return L = [4,6].

Here is my attempt:

gt(_,[],[]):-!.
gt(Num,[H|T],[H|L]):-
    Num>H,  
    gt(Num,T,L).
gt(Num,[H|T],[H|L]):-
    Num=<H,!,  
    gt(Num,T,L).

The problem that I am facing is in the =< predicate. If the condition is =< the number, then I am trying to say that ignore and move to the next number gt(Num,T,L). The place where I have written L, what should I write here so that it understands that I don't want you to write that value in the list? Works alright for values that are already smaller than the number.

?-gt(12,[6,7,6],L).
L = [6,7,6]

But fail for such tests:

?- gt(12,[19,6,7],L).
L = [19, 6, 7]

Solution

  • The problem is in the third parameter in the third clause of gt/3. It is also "adding" the current item H as the head of the output list. You should write

    gt(Num,[H|T],L):-
        Num=<H,!,  
        gt(Num,T,L).
    

    instead.

    You may also get rid of those cuts (!) to make your procedure work with other modes for the parameters and/or with uninstantiated variables.