prologdifference-lists

Difference list with (-)/2 operator


I am currently taking a Prolog course.

I'm familiar with the [A|B] notation of lists in Prolog, but the teacher shows that [a,b,c|X]-X is also a valid way of having a list, where we have a reference to the tail of the list. When I try it out with Swi-Prolog however, I receive the following error: ERROR: Undefined procedure: (-)/2 (DWIM could not correct goal).

Is the (-)/2 operator just defined in standard Prolog but not in Swi-Prolog or am I missing something ?


Solution

  • This structure is called difference list. (https://en.wikibooks.org/wiki/Prolog/Difference_Lists)

    Probably you used '-' wrong. Let's consider append predicate on difference lists:

    app(X-Y, Y-Z, X-Z).
    

    You can test it like this (after compiling file having this predicate):

    ?- app([1,2,3|A]-A, [4, 5|B]-B, C).
    

    [1,2,3|A]-A can be considered as [1,2,3] and [4, 5|B]-B can be considered as [4,5], so having output:

    A = [4, 5|B],
    C = [1, 2, 3, 4, 5|B]-B.
    

    You can see, that C became [1, 2, 3, 4, 5|B]-B that can be considered as [1,2,3,4,5].

    Little visualization of what's going on there:

     <-------------------X--------------------->
                   <-------------Y------------->
                                  <-----Z------>
    ||............||.............||............||   <- List
     <--- X-Y ----><---- Y-Z ---->
     <---------- X-Z ------------>