【发布时间】:2020-02-09 12:04:52
【问题描述】:
我有一个小问题,我需要编写一个 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 recursion functional-programming binary-tree