如何在 Haskell 中显示递归数据类型(树)的每个元素
How to show every elements of a recursive data type (Tree) in Haskell
我有一个小问题,我需要编写一个 show 实例来打印树的递归数据中的每个元素:
-- | A binary tree representing a series-parallel graph
data SpTree a
-- | Leaf node
= LeafNode a
-- | Series composition
| SeriesNode a (SpTree a) (SpTree a)
-- | Parallel composition
| ParallelNode a (SpTree a) (SpTree a)
-- | An SP-tree can be shown
--
-- >>> show $ LeafNode 1
-- "Leaf 1"
-- >>> show $ SeriesNode 1 (LeafNode 2) (LeafNode 3)
-- "Ser 1 (Leaf 2) (Leaf 3)"
-- >>> show $ ParallelNode 1 (LeafNode 2) (LeafNode 3)
-- "Par 1 (Leaf 2) (Leaf 3)"
instance Show a => Show (SpTree a) where
show = ?
定义此实例的最佳方式是什么?我应该使用模式匹配还是守卫?
我为 leafNode 尝试了这个,但它给了我一个错误提示
Data constructor not in scope: LeafNode :: Integer -> ()
当我尝试 运行 这一行时:show $ LeafNode 1
instance Show a => Show (SpTree a) where
show (a)
| LeafNode a = show a :: Integer
谢谢!
我在 Haskell 还是个新手,但这样的方法行得通吗?
module Main where
import Data.List
data SpTree a
-- | Leaf node
= LeafNode a
-- | Series composition
| SeriesNode a (SpTree a) (SpTree a)
-- | Parallel composition
| ParallelNode a (SpTree a) (SpTree a)
parens :: String -> String
parens a = "(" ++ a ++ ")"
instance Show a => Show (SpTree a) where
show (LeafNode x) = "Leaf " ++ show x
show (SeriesNode x y z) =
unwords ["Ser", show x, parens $ show y, parens $ show z]
show (ParallelNode x y z) =
unwords ["Par", show x, parens $ show y, parens $ show z]
main = do
putStr $ show $ LeafNode 1
我有一个小问题,我需要编写一个 show 实例来打印树的递归数据中的每个元素:
-- | A binary tree representing a series-parallel graph
data SpTree a
-- | Leaf node
= LeafNode a
-- | Series composition
| SeriesNode a (SpTree a) (SpTree a)
-- | Parallel composition
| ParallelNode a (SpTree a) (SpTree a)
-- | An SP-tree can be shown
--
-- >>> show $ LeafNode 1
-- "Leaf 1"
-- >>> show $ SeriesNode 1 (LeafNode 2) (LeafNode 3)
-- "Ser 1 (Leaf 2) (Leaf 3)"
-- >>> show $ ParallelNode 1 (LeafNode 2) (LeafNode 3)
-- "Par 1 (Leaf 2) (Leaf 3)"
instance Show a => Show (SpTree a) where
show = ?
定义此实例的最佳方式是什么?我应该使用模式匹配还是守卫?
我为 leafNode 尝试了这个,但它给了我一个错误提示
Data constructor not in scope: LeafNode :: Integer -> ()
当我尝试 运行 这一行时:show $ LeafNode 1
instance Show a => Show (SpTree a) where
show (a)
| LeafNode a = show a :: Integer
谢谢!
我在 Haskell 还是个新手,但这样的方法行得通吗?
module Main where
import Data.List
data SpTree a
-- | Leaf node
= LeafNode a
-- | Series composition
| SeriesNode a (SpTree a) (SpTree a)
-- | Parallel composition
| ParallelNode a (SpTree a) (SpTree a)
parens :: String -> String
parens a = "(" ++ a ++ ")"
instance Show a => Show (SpTree a) where
show (LeafNode x) = "Leaf " ++ show x
show (SeriesNode x y z) =
unwords ["Ser", show x, parens $ show y, parens $ show z]
show (ParallelNode x y z) =
unwords ["Par", show x, parens $ show y, parens $ show z]
main = do
putStr $ show $ LeafNode 1