Haskell显示没有Data.Tree或派生的Tree(显示)

编程入门 行业动态 更新时间:2024-10-25 18:31:20
本文介绍了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(显示)

本文发布于:2023-11-30 05:21:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648862.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Haskell   Data   Tree

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!