Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data type for Tree in Haskell

Tags:

types

haskell

For a data type of a binary tree you can write something like this:

data Tree a = Nil | Node a (Tree a) (Tree a)

So if I do want to include trees, with Nodes having more than just two children, how could the data type possibly look like?

like image 481
SOAP Avatar asked Dec 31 '16 13:12

SOAP


People also ask

What data type is a tree?

ADTs (Abstract Data Types) which follow a hierarchical pattern for data allocation is known as 'trees. ' A tree is essentially a collection of multiple nodes connected by edges.

How do I encode a tree in Haskell?

You can construct a Huffman Encoding Tree by passing a list of Leaf Nodes that is sorted by the Weight of each Leaf to makeTree like this. makeTree works by taking the two Nodes with with smallest weights from the list and combining them into a new Node then inserting the new Node into the list in the correct position.


2 Answers

A lesser known technique is Left-child right-sibling where you can use the exact same type to encode trees with more than two children per node:

left-child-right-sibiling

data Tree a
  = Nil
  | Node a (Tree a) (Tree a) -- value, left child, right sibling

The alternative [Tree a] does not have a performance advantage, since Haskell lists are linked lists.

like image 146
behzad.nouri Avatar answered Dec 05 '22 00:12

behzad.nouri


You can either have a fixed branching factor:

data BinaryTree a  = BTNil 
                   | BTNode a (BinaryTree a) (BinaryTree a)

data TernaryTree a = TTNil
                   | TTNode a (TernaryTree a) (TernaryTree a) (TernaryTree a)

data QuadTree a    = QTNil
                   | QTNode a (QuadTree a) (QuadTree a) (QuadTree a) (QuadTree a)

-- etc

(Note that QuadTree isn't a great name for a general tree with a branching factor of 4, since there is a specific data structure with that name.)

or you can simply use a rose tree, which stores an arbitrary list of children at each node.

data RoseTree a = RTNil | RTNode a [RoseTree a]

There is some duplication here, as RTNil is only needed to store an explicit empty tree. Leaf nodes are just RTNode a []. (Consider what difference, if any, you would assign to the values RTNode 3 [], RTNode 3 [RTNil], RTNode 3 [RTNil, RTNil], etc.)

like image 32
chepner Avatar answered Dec 04 '22 22:12

chepner