listprologdifference-lists

Prolog: Graph representation of list and difference list


I've been trying to understand how a list and a difference list would look like in a graph structure. I understand the basic structure of a list like [a1,a2,a3,..an|[]].

arbitrary list

But I can't grasp how a difference list would look like?

like for example [1,2,3,4]-[3,4]


Solution

  • X-Y is the term -(X, Y). So [1,2,3,4]-[3,4] is primarily just a pair of two lists, each of which can be readily displayed in a tree like the one you show.

    Consider now a list of the form [E1,E2,...,E_n|Rest], that is, where the final tail is not yet instantiated. Again, you can readily display this in a tree like the one you show, just replace end-of-list (which is wrong anyway, because it should actually be the atom nil: []) by Rest.

    The idea is now to always keep track of the tail that is not yet instantiated, which is a single logical variable. By instantiating this variable, again to a list whose tail is not yet instantiated and of whose tail you again keep track separately, you can always append further elements, in time independent of the length that the original list has already reached.

    You can represent such a list and its final tail as the pair [E1,E2,...,E_n|Rest]-Rest, but it's actually preferable to use two different arguments and pass around the list and its uninstantiated final tail as two separate arguments (explanation).