简体   繁体   English

打印出一棵玫瑰树……?

[英]Printing out a rose tree…?

I am currently learning Haskell in one of my online classes at the university.我目前正在大学的一门在线课程中学习 Haskell。 I now have to write a program that can work with a rose tree.我现在必须编写一个可以处理玫瑰树的程序。 Right now it looks like this:现在它看起来像这样:

data Rose a = Rose a [Rose a]

testTree1 = Rose 4 [Rose 5 [Rose 1 [], Rose 2 [Rose 7 [], Rose 8 []], Rose 3 []], Rose 6 []]

class Pretty a where
    pretty :: a -> String


instance Pretty (Rose a) where
    pretty (Rose v []) = "Test"
    pretty (Rose v t ) = "Test" ++ (concat(map ("\n+--"++) (map (pretty) t)))

On calling putStrLn (pretty (testTree1)) the result should look like this:在调用putStrLn (pretty (testTree1))时,结果应如下所示:

4
+-- 5
|   +-- 1
|   +-- 2
|   |   +-- 7
|   |   +-- 8
|   +-- 3
+-- 6

My current function has the following result:我当前的 function 有以下结果:

Test
+--Test
+--Test
+--Test
+--Test
+--Test
+--Test
+--Test

So I have these two questions.所以我有这两个问题。

  1. How can I put the real value of v in the String instead of the placeholder Test , when I don't know which type the v will have?当我不知道v将具有哪种类型时,如何将v的实际值放入 String 而不是占位符Test
  2. I don't understand why the Test s in my result all have the same alignment.我不明白为什么我的结果中的Test都具有相同的 alignment。 Of course I am not using the |当然我没有使用| yet, but shouldn't the +-- appear more than one time in some lines?但是,但是+--在某些行中不应该出现多次吗?

Thx for your help:)谢谢你的帮助:)

If you want to use the value of v in the output, then Rose a only has a Pretty instance if a does as well, in which case you can use pretty to convert v .如果你想在 output 中使用v的值,那么Rose a只有一个Pretty实例,如果a也有,那么你可以使用pretty来转换v

instance Pretty a => Pretty (Rose a) where
    pretty (Rose v []) = pretty v
    pretty (Rose v t ) = pretty v ++ concat(map ("\n+--"++) (map pretty t)))

For your example, you also need to provide a concrete type for testTree1 and to define an appropriate instance for Pretty .对于您的示例,您还需要为testTree1提供一个具体类型并为Pretty定义一个适当的实例。 For example,例如,

testTree1 :: Rose Int
testTree1 = ...

instance Pretty Int where
    pretty = show

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM