Search code examples
prologclpfd

How to prune wrong answers? Is my code wrong?


So I've tried to make my item_list_itemCount relation the most general possible and it indeed works, at least until a certain point. Here's the code:

% associates an item, a list and the number of times the item appears in that list.
item_list_count(_ , [], 0).
item_list_count(Item, [Item|T], Count) :-
    TCount #>= 0, 
    Count #= TCount + 1, 
    item_list_count(Item, T, TCount).
item_list_count(Item, [_|T], Count) :- 
    Count #>= 0,
    item_list_count(Item, T, Count).

For example, the query item_list_count(1, [1,1,1,2,2,3], Count). gives a right first solution and other wrong solution on backtracking.

?- item_list_count(1, [1,1,1,2,2,3], Count).
Count = 3 ;
Count = 2 ;
Count = 2 ;
Count = 1 ;
Count = 2 ;
Count = 1 ;
Count = 1 ;
Count = 0 ;
false.

I have a few hypotheses about why that is. Prolog doesn't know beforehand that 1 could show up exactly N times so it tries to apply itself recursively to each sublist. However, the number of solutions is not the same number of sublists(there are 7 in total) and I get 8 answers.

I'd also like to extend this question to ask about a good, robust and complete textbook on prolog. I've been asking many questions lately and I've realized that my lack of knowledge is putting at loss while programming in prolog, so I'd like to not have any holes in my knowledge. Are there any reliable books out there that a CS undergrad on his 6th semester can use?

Thanks in advance!


Solution

  • Your third clause triggers on backtracking. Something like this could prevent that:

    item_list_count(Item, [NotItem|T], Count) :- 
        Item \= NotItem,
        item_list_count(Item, T, Count).
    

    For every duplicate you have 2 choice points. And hence for three 1s you have 2^3 = 8 solutions. It is not related to the size of the list itself.

    You can also commit to the second clause itself.

    item_list_count(Item, [Item|T], Count) :-
        !,                                  % prune the choice points 
        ...