打印列表,空格而不是逗号

时间:2015-05-05 14:12:22

标签: list haskell

我遇到了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)

但我无法将其整合到我的功能中。

2 个答案:

答案 0 :(得分:3)

你几乎完成了所有事情。但要使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 

答案 1 :(得分: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)