【问题标题】:How to show every elements of a recursive data type (Tree) in Haskell如何在 Haskell 中显示递归数据类型(树)的每个元素
【发布时间】: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


【解决方案1】:

我还是 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

【讨论】:

    猜你喜欢
    • 2016-09-20
    • 2015-01-07
    • 2014-06-24
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-30
    • 2018-07-11
    相关资源
    最近更新 更多