apoorv020
apoorv020

Reputation: 5670

Good way to declare trees in prolog?

I am working with trees (general trees, not limited to binary) in prolog. From the small snippets of code I have seen, though it's easy to define traversals etc. on the tree, it's not easy to define an instance of a tree. What would be a good way to do this? Also, how should I try to include single-attribute values with each node?

Upvotes: 2

Views: 6435

Answers (2)

mat
mat

Reputation: 40768

Regarding your comment "But the problem is that the whole tree has to go in one line": This is not the case. You can also use several lines to construct a tree, for example:

tree(Tree) :-
    Tree = tree(Root, [Child,Leaf3]).
    Child = tree(Node1, [Leaf1,Leaf2]),
    Leaf1 = tree(Node2, []),
    Leaf2 = tree(Node3, []),
    Leaf3 = tree(Node4, []).

Upvotes: 4

Nicholas Carey
Nicholas Carey

Reputation: 74325

Is this homework?

The simple way to represent an arbitrary tree structure, IMHO, would be to represent each node as something something like:

tree(Data,[ChildNode_1,...,ChildNode_n]).

Leaf nodes would look like:

tree(Data,[]).

A binary tree, being slightly specialized, might look like

tree(Data,LeftChild,RightChild).

with the atom nil representing a non-existent child node, so its leaf nodes would look like

tree(Data,nil,nil).

And a node with only a left child like

tree(Data,LeftChild,nil).

Node data can be any arbitrary structure. Perhaps you want it to be a key/value pair:

tree(kvp(Key,Value),ChildNodes).

Upvotes: 4

Related Questions