我发现自己处于这样一种情况下,我要定义的类型类实例需要额外的类型约束。具体来说,我想定义
Show
对于某种类型
Trie a
:
data Trie a = Node {
label :: a,
edges :: DM.Map a (Trie a),
isFinal :: Bool
}
而Show的实例是:
import qualified Data.Tree as DT
instance (Show a, Eq a, Eq (Trie a)) => Show (Trie a) where
show trie@(Node label edges _) = DT.drawTree (mapTree show $ toDataTree trie)
我需要
Eq a
和
Eq (Trie a)
这里,正如我使用的
toDataTree
它转换了
特里亚
到A
DT.Tree a
并包含这些类型约束:
import qualified Data.Map as DM
toDataTree :: (Eq a, Eq (Trie a)) => Trie a -> DT.Tree a
toDataTree (Node label edges isFinal)
| edges == DM.empty = DT.Node label (map toDataTree (DM.elems edges))
| otherwise = DT.Node label []
mapTree :: (a -> b) -> DT.Tree a -> DT.Tree b
mapTree f (DT.Node rootLabel subForest) = DT.Node (f rootLabel) $ map (mapTree f) subForest
当它编译时,当我真的想调用
print
在一
特里亚
(何处)
a
=
Char
在这种情况下)我得到
⢠No instance for (Eq (Trie Char)) arising from a use of âprintâ
⢠In a stmt of an interactive GHCi command: print it
这必须是因为我需要将这些附加类型约束添加到
秀
. 所以我的方法可能是错误的。
对于类型类实例定义所需的其他类型约束,正确的解决方案是什么?