Cia*_*ran 6 formatting haskell
嘿.对于本周的教程,其中一个问题要求通过使用其他函数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
Run Code Online (Sandbox Code Playgroud)
代码看起来(至少对我来说)它应该工作,但不是创建一个新的行,其中"\n",\n被附加到字符串.
任何帮助将不胜感激.
Ste*_*202 21
那是因为您可能正在使用print
打印结果.相反,使用putStr
.注意:
Prelude> print "test\ntest\n"
"test\ntest"
Prelude> putStr "test\ntest\n"
test
test
Run Code Online (Sandbox Code Playgroud)
除此之外,您可以使用模式匹配来编写formatList
而不使用head
和tail
:
formatList :: (a -> String) -> [a] -> String
formatList f [] = []
formatList f (x:xs) = f x ++ formatList f xs
Run Code Online (Sandbox Code Playgroud)
但实际上没有必要定义formatList
自己,因为它与函数相同concatMap
:
formatList :: (a -> String) -> [a] -> String
formatList = concatMap
Run Code Online (Sandbox Code Playgroud)
结合所有这些,你也可以写(注意这(++ "\n")
是一节):
formatLines :: [String] -> String
formatLines = concatMap (++ "\n")
Run Code Online (Sandbox Code Playgroud)
......反过来相当于unlines
:
formatLines :: [String] -> String
formatLines = unlines
Run Code Online (Sandbox Code Playgroud)