本文介绍了Haskell显示没有Data.Tree或派生的Tree(显示)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,我的实例在显示Haskell中的树时遇到问题:这是我的代码:
Hi guys I'm having an issue with my instance to show a tree in Haskell: here is my code:
data Tree a b = Branch b (Tree a b) (Tree a b) | Leaf a instance (Show a, Show b) =>Show (Tree a b) where show (Leaf x) = " "++show x ++"\n" show (Branch val l r) = show val ++ "\n" ++" " ++ show l ++ " " ++ show r这是我的测试用例和输出(这是错误的):
here is my test case and output( which is wrong):
Branch "<" (Branch "<" (Leaf 'a') (Leaf 'c')) (Branch "<" (Leaf 'g') (Branch "<" (Leaf 'n') (Leaf 'y')))) "<" "<" 'a' 'c' "<" 'g' "<" 'n' 'y'正确的输出
"<" "<" 'a' 'c' "<" 'g' "<" 'n' 'y'任何帮助都会很棒!
推荐答案您的显示功能无法知道每行缩进的深度.在子树前面加一个空格是行不通的,因为它们通常会有多于一行.
Your display function has no way of knowing how deeply to indent each line. Prepending a space to your subtrees won't work because they will generally have more than one line.
您需要定义一个以缩进为参数的辅助功能:
You need to define an auxiliary function which takes the indentation as a parameter:
indent n x = concat (replicate n " ") ++ show x ++ "\n" f n (Leaf x) = indent n x f n (Branch val l r) = indent n val ++ f (n+1) l ++ f (n+1) r instance (Show a, Show b) => Show (Tree a b) where show tree = f 0 tree更多推荐
Haskell显示没有Data.Tree或派生的Tree(显示)
发布评论