Nicely printing/showing a binary tree in Haskell

前端 未结 3 491
故里飘歌
故里飘歌 2021-02-05 07:33

I have a tree data type:

data Tree a b = Branch b (Tree a b) (Tree a b) | Leaf a

...and I need to make it an instance of Show, wit

3条回答
  •  一向
    一向 (楼主)
    2021-02-05 08:18

    You might study the drawTree function in the base Data.Tree module. Just shamelessly importing it would give you something like this:

    import Data.Tree hiding (Tree )
    data Tree a b = Branch b (Tree a b) (Tree a b) 
                  | Leaf a deriving (Eq,Ord,Show)
    
    toDataTree (Leaf a) = Node a []
    toDataTree (Branch b cs ds) = Node b [toDataTree cs, toDataTree ds]
    
    d = Branch "1" (Branch "11" (Leaf "111") (Leaf "112")) 
                   (Branch "12" (Leaf "121") (Leaf "122"))
    
    e = toDataTree d
    f = putStrLn $ drawTree e
    
    {-
    *Main> f
    1
    |
    +- 11
    |  |
    |  +- 111
    |  |
    |  `- 112
    |
    `- 12
       |
       +- 121
       |
       `- 122
    -}
    

提交回复
热议问题