Search code examples
recursionfilterprologlogic

How can i filter a list by 2 conditions?


I'm new to prolog and i can't find a solution to filter list by 2 conditions, save result into 2 variables and then evaluate answer base on them.
In my case, if list contains more numbers that greater then 0, then numbers lesser then 0.

For example i get a list with elements:

checklist([-2, 3.3, 12, -10.1, 14, -11, 123]) # true
checklist([-2.1, -3, -4, 14, 16.7])           # false
checklist([11.5, 2.5, -34.1, -1])             # false

I'd write something like this in python:

bigger_count = 0
lesser_count = 0
for num in list:
    if num > 0:
        bigger_count += 1
    elif num < 0:
        lesser_count += 1
print(bigger_count > lesser_count)

Especially i doesn't understand how to work with 2 variables at one time.


Solution

  • Another possible solution is:

    check(List) :-
        check(List, Balance),
        Balance > 0.
    
    check([], 0).
    check([X|Xs], B) :-
        check(Xs, B0),
        (   X > 0 -> B is B0 + 1
        ;   X < 0 -> B is B0 - 1
        ;            B is B0 ).
    

    Examples:

    ?- check([-2, 3.3, 12, -10.1, 14, -11, 123]).
    true.
    
    ?- check([-2.1, -3, -4, 14, 16.7]).
    false.
    
    ?- check([11.5, 2.5, -34.1, -1]).
    false.
    
    ?- check([1,-1]).
    false.