【问题标题】:How to specify the type of arguments given to Algebraic type in Haskell如何在 Haskell 中指定代数类型的参数类型
【发布时间】:2023-03-04 03:57:01
【问题描述】:

如果我有如下所示的代数数据类型

data BinaryTree a = Leaf 
                    | Node a (BinaryTree a ) (BinaryTree a)
                    deriving (Eq,Ord)

这里的叶子是空的,a是节点,另外两个参数是来自节点的子树。

有没有办法可以指定参数 a 应该派生 Show

我试图为 BinaryTree 提供我自己的 Show 实现,我一开始很简单:

instance Show (BinaryTree a) where
    show Leaf = "x"
    show (Node node left right) =  show node++ "\n" ++ show left ++"  "++show right

但是show node 不起作用 -> No instance for (Show a) arising from a use of ‘show’

【问题讨论】:

    标签: haskell


    【解决方案1】:

    如果node 属于Show 类型类的成员,则只能使用show node。因此,您应该在 instance 声明的头部添加一个类型约束:

    --         ↓ type constraint
    instance Show a => Show (BinaryTree a) where
        show Leaf = "x"
        show (Node node left right) =  show node ++ '\n' : show left ++ "  "++show right

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-04
      • 1970-01-01
      • 2017-04-11
      • 2011-11-26
      • 1970-01-01
      • 2012-05-15
      • 1970-01-01
      相关资源
      最近更新 更多