新线Haskell

时间:2009-11-18 12:49:42

标签: haskell formatting

嘿。对于本周的教程,其中一个问题要求通过使用其他函数formatLine和formatList来创建函数formatLines,以格式化行列表。

我的代码看起来像这样;

type Line = String

formatLine :: Line -> String
formatLine l = l ++ "\n"

formatList :: (a -> String) -> [a] -> String
formatList f [] = []
formatList f xs = f (head xs) ++ formatList f (tail xs)

formatLines :: [Line] -> String
formatLines xs = formatList formatLine xs

代码看起来(至少对我来说)它应该可以工作,但不是创建一个新的行,其中“\ n”,\ n被附加到字符串。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:21)

这是因为您可能正在使用print来打印结果。相反,请使用putStr。观察:

Prelude> print "test\ntest\n"
"test\ntest"
Prelude> putStr "test\ntest\n"
test
test

除此之外,您可以使用模式匹配来编写formatList而不headtail

formatList :: (a -> String) -> [a] -> String
formatList f [] = []
formatList f (x:xs) = f x ++ formatList f xs

但实际上没有必要自己定义formatList,因为它与函数concatMap相同:

formatList :: (a -> String) -> [a] -> String
formatList = concatMap

结合所有这些,你也可以写(注意(++ "\n")section):

formatLines :: [String] -> String
formatLines = concatMap (++ "\n")

...反过来相当于unlines

formatLines :: [String] -> String
formatLines = unlines

答案 1 :(得分:0)

试试

formatLines = unwords