Search code examples
prolog

SWI Prolog list subtract gives error: Out of local stack


I'm running some Prolog rule which uses the subtract function and in the stack trace, I found the source of error to be this:

lists:subtract([b, d | _], [b, d] , [r]) ? creep
ERROR: Out of local stack

The original call was:

member(b, X), member(d, X), subtract(X, [b, d], [r]).

and the expected output is [b, d, r].

I'm new to Prolog and unable to understand the source of error and how to fix it. Please help.


Solution

  • From SWI Prolog manual :

    The library(lists) contains a number of old predicates for manipulating sets represented as unordered lists, notably intersection/3, union/3, subset/2 and subtract/3. These predicates all use memberchk/2 to find equivalent elements. As a result these are not logical while unification can easily lead to dubious results.

    You are having this problem because subtract isn't pure and needs it's first two Arguments to be instantiated hence the + sign in it's documentation .

    subtract(+Set, +Delete, -Result)
    

    you can instead use union/3

    union(+Set1, +Set2, -Set3)
    

    you can know more about other mode indicators in here.