I\'m reading this tutorial on context free grammars in Prolog, and they mention at the bottom of the page implementing a context free grammar in Prolog using difference list
Difference lists work like this ( a layman's explanation).
Consider append is used to join two trains X
and Y
X = {1}[2][3][4] Y = {a}[b][c]
{ }
- represents the compartment having the engine or head.
[ ]
- represents compartments or elements in the tail. Assume that we can remove the engine from one compartment and put it into another.
Append proceeds like this:
The new train Z
is now Y
i.e., {a}[b][c]
next the engine is removed from Z
's head and put into tail end compartment removed from X and the new train Z
is:
Z = {4}[a][b][c]
The same process is repeated
Z = {3}[4][a][b][c]
Z = {2}[3][4][a][b][c]
Z = {1}[2][[3][4][a][b][c]
our new long train.
Introducing Difference lists is like having a toa hook at the end of X that can readily fasten to Y. The final hook is discarded.
n([man|W],W).
W
is the hook here, unification of W
with the head of the successor list is the fastening process.