For educational purposes I am playing around with trees in Haskell. I have Tree a
type defined like this
data Tree a = EmptyTree | Node a (Tree a) (Tree a)
and a lot of functions that share a basic constraint - Ord a
- so they have types like
treeInsert :: Ord a => a -> Tree a -> Tree a
treeMake :: Ord a => [a] -> Tree a
and so on. I can also define Tree a
like this
data Ord a => Tree a = EmptyTree | Node a (Tree a) (Tree a)
but I can not simplify my functions and omit the extra Ord a
to be as the following:
treeInsert :: a -> Tree a -> Tree a
treeMake :: [a] -> Tree a
Why does Haskell (running with -XDatatypeContexts
) not automatically deduce this constraint? It seems to to be quite obvious for me that it should. Why am I wrong?
Here is some example source code
data (Eq a, Ord a) => Tree a = EmptyTree | Node a (Tree a) (Tree a)
treeInsert :: a -> Tree a -> Tree a
treeInsert a EmptyTree = Node a EmptyTree EmptyTree
treeInsert a node@(Node v left right)
| a == v = node
| a > v = Node v left (treeInsert a right)
| a < v = Node v (treeInsert a left) right
mkTree :: [a] -> Tree a
mkTree [] = EmptyTree
mkTree (x:xs) = treeInsert x (mkTree xs)
I am getting this
Tree.hs:5:26:
No instance for (Ord a)
arising from a use of `Node'
In the expression: Node a EmptyTree EmptyTree
In an equation for `treeInsert':
treeInsert a EmptyTree = Node a EmptyTree EmptyTree
Failed, modules loaded: none.
Eq
andOrd
in a context.Eq
is a superclass ofOrd
, so the latter is enough. – augustss