出于教育目的,我在 Haskell 中玩树木。我有Tree a
这样定义的类型
data Tree a = EmptyTree | Node a (Tree a) (Tree a)
以及许多共享基本约束的函数Ord a
--因此它们具有以下类型
treeInsert :: Ord a => a -> Tree a -> Tree a
treeMake :: Ord a => [a] -> Tree a
等等。我也可以Tree a
这样定义
data Ord a => Tree a = EmptyTree | Node a (Tree a) (Tree a)
但我不能简化我的功能并省略额外Ord a
的如下:
treeInsert :: a -> Tree a -> Tree a
treeMake :: [a] -> Tree a
为什么 Haskell(与 一起运行-XDatatypeContexts
)不会自动推断出这个约束?对我来说,这似乎很明显。为什么我错了?
这是一些示例源代码
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)
我得到这个
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.