【发布时间】:2018-09-06 06:15:39
【问题描述】:
我发现自己处于我想要定义的类型类实例需要额外类型约束的情况。具体来说,我想为Trie a 类型定义Show:
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 将Trie 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
虽然这确实可以编译,但当我真正想在 Trie a 上调用 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
这一定是因为我需要将这些额外的类型约束添加到Show 的实例中。所以我的方法可能是错误的。
对于类型类实例定义所需的附加类型约束,正确的解决方案是什么?
【问题讨论】:
标签: haskell constraints typeclass