【问题标题】:Print list with space rather comma打印带有空格而不是逗号的列表
【发布时间】:2015-05-05 14:12:22
【问题描述】:

我对 Haskell 的一个功能有疑问:将树转换为列表后,我需要打印它,并使用空格而不是逗号分隔的项目。

例如:

data Tree a = Empty | Branch a (Tree a) (Tree a)
              deriving (Show, Eq)

tree4 = Branch 1 (Branch 2 Empty (Branch 4 Empty Empty)) (Branch 2 Empty Empty)

leaves :: Tree a -> [a]
leaves  Empty                 = []
leaves (Branch a Empty Empty) = [a]
leaves (Branch a left  right) = leaves left ++ leaves right

结果是:

*Main> leaves tree4 
[4,2]

但我希望结果是:

*Main> leaves tree4 
 4 2
*Main>

我该怎么做?

我想,首先,以这种方式覆盖类显示:

newtype SimpleRecords = SimpleRecords [Integer]

instance Show SimpleRecords where
  show (SimpleRecords []) = ""
  show (SimpleRecords (x:xs)) = show x ++ " " ++ show (SimpleRecords xs)

但我无法将它集成到我的功能中。

【问题讨论】:

  • 为什么没有leaves :: Tree a -> String?或者编写一个函数listToString :: [a] -> String(如果这样的函数不存在)并调用listToString $ leaves tree4
  • 试试unwords $ map show $ leaves tree4。或者,您可以在 show = unwords . map show . leaves 的位置创建 Show a => Show (Tree a) 实例,这将完全满足您的需求。

标签: list haskell


【解决方案1】:

您几乎完成了所有工作。但是要使SimpleRecordsTree 兼容,您必须摆脱Integer 并使其具有多态性。

newtype SimpleRecords a = SimpleRecords [a]

instance Show a => Show (SimpleRecords a) where
    show (SimpleRecords []) = ""
    show (SimpleRecords (x:xs)) = show x ++ " " ++ show (SimpleRecords xs)

现在将您的 leaves 函数更改为发出 SimpleRecords

leaves :: Tree a -> SimpleRecords a
leaves xs = SimpleRecords $ aux xs
    where
      aux  Empty                 = []
      aux (Branch a Empty Empty) = [a]
      aux (Branch a left  right) = aux left ++ aux right

ghci中的演示:

λ> leaves tree4 
4 2 

【讨论】:

    【解决方案2】:
    data Tree a = Empty | Branch a (Tree a) (Tree a)
                  deriving (Show, Eq)
    
    tree4 = Branch 1 (Branch 2 Empty (Branch 4 Empty Empty)) (Branch 2 Empty Empty)
    
    leaves :: Tree a -> SimpleRecords a
    leaves  Empty                 = SimpleRecords []
    leaves (Branch a Empty Empty) = SimpleRecords  [a]
    leaves (Branch a left  right) = SimpleRecords (left' ++ right')
        where
            SimpleRecords left' = leaves left
            SimpleRecords right'= leaves right
    
    newtype SimpleRecords a = SimpleRecords [a]
    
    instance (Show a)=>Show (SimpleRecords a) where
      show (SimpleRecords []) = ""
      show (SimpleRecords (x:xs)) = show x ++ " " ++ show (SimpleRecords xs)
    

    【讨论】:

      猜你喜欢
      • 2023-01-17
      • 2014-03-06
      • 2017-11-22
      • 1970-01-01
      • 1970-01-01
      • 2011-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多