I'm reading Purely Functional Data Structres and trying to solve exercises they give in haskell.
I've defined Tree
in a standard way data Tree a = Empty | Node a (Tree a) (Tree a)
I'd like to define Set
as Tree
where nodes are instance of Ord
. Is there a way to express this in Haskell? Something like type Set = Tree Ord
or I deemed to reimplement tree every time I want express some data structure as tree?
Do you intend to use the tree as a binary search tree (BST)? For that to work, you need all operations to preserve the strong BST property: for each Node
constructor in the BST, all Node
s in the left subtree contain elements less than the one in the current Node
, all Node
s in the right subtree contain elements greater.
You absolutely need to preserve that property. Once it's no longer true, all further BST operations lose correctness guarantees. This conclusion has consequences. You can't expose the constructors of the type. You can't expose operations to work on it that don't preserve the BST property.
So every operation that operates on a set needs to have access to the Ord
instance for the type constrained in the node. (Well, other than a couple special cases like checking if a set is empty or creating a singleton set, which never have to deal with the order of children.)
At that point, what exactly can you share about the tree type with other uses? You can't share operations. You can't use the constructors. That leaves, well.. nothing useful. You could share the name of the type with no ways to do much of anything with it.
So, no.. You can't share a binary search tree data type with other uses that just seek an arbitrary binary tree. Attempting to do so just results in a broken BST.