I have been learning Prolog in my spare time for about 8 months to a year and now I am moving on to tackle implementing some of the classic data structures and algorithms .
I am interested in achieving a doubly linked list in Prolog, but quite baffled as to how to proceed . I was attracted to Prolog because I am interested in "logical purity" .
It seems that I am so accommodated to the object-oriented paradigm that beyond the simple I just cannot proceed without it !
For reference by doubly linked list I mean something similar to what is described in this link :
What makes it a doubly-linked list is that it has two links rather than one, a reference to the previous and the next item in the list. So we could make a
node(Value, Previous, Next)struct and make the list manually like so:A = node(1, nil, B), B = node(2, A, nil).. We could make longer lists the analogous way, just creating more intermediate variables.Translating that back into a "normal" list would look something like this:
This makes no particular use of the "previous" pointer, but you can see it works:
We could also build backwards, starting from the end:
To construct a doubly-linked list from a list, you need something a little stronger than either of these:
This you can see working in both directions here:
and here: