【发布时间】: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)实例,这将完全满足您的需求。