haskell - 我可以部分导出 Show 吗?

标签 haskell

我编写了这段代码来漂亮地打印一棵树:

data Node = A | B | C | Tree Node [Node]
    deriving (Show, Eq)

printTree' :: Int -> Node -> [String]
printTree' spaceCount (Tree node children) = (printTree' spaceCount node)
    ++ concat (map (\child -> printTree' (spaceCount+2) child) children)
printTree' spaceCount leaf = [(replicate spaceCount ' ') ++ (show leaf)]

printTree :: Node -> String
printTree node = unlines (printTree' 0 node)

示例输出:

*Main> putStr $ printTree $ Tree A [Tree A [A,B,C], C]
A
  A
    A
    B
    C
  C

现在我想将其作为 show 的实现。这种方法很接近,但我找不到调用内置 show 的方法:

instance Show Node where
    show (Tree node children) = printTree (Tree node children)
    show _ = "node... can I call the built-in show here?"

(在这个例子中,我可以只处理A、B和C。但在实际代码中,有很多节点类型。)

最佳答案

我认为做到这一点的唯一方法是将其分为两种类型。

data Tree node = Tree node [Tree node]
data Node = A | B | C deriving Show

instance Show node => Show (Tree node) where ....

关于haskell - 我可以部分导出 Show 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31249175/

相关文章:

haskell - Data.Aeson 中的模式匹配向量值

haskell - 使用Aeson时如何使用sum类型作为map中的键?

haskell - 类型 [[a]] -> ([a], [a]) 的法则

haskell - 为什么 rank-n 类型需要显式的 forall 量词?

haskell - 什么是 Addr# 类型,如何使用它?

opencv - 如何在 Haskell 中使用 fromPtr 正确构建 Accelerate 数组?

haskell - 计算递归次数

haskell - Cabal 可以找到给定软件包集的匹配版本吗?

haskell - Haskell 中双序列和位遍历之间的关系如何运作?

haskell - 作为类型构造函数的符号名称