2009-11-18 20 views
6

嘿。對於本週的教程,其中一個問題要求通過使用其他函數formatLine和formatList來創建函數formatLines,以格式化行列表。新線Haskell

我的代碼看起來像這樣;

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

'formatList = map' – Chuck

回答

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 
+0

unlines,而不是unwords。使用任何一種都不是遵循教程的精神,而是用於指出已有的功能。 – Nefrubyr

+0

@Nefrubyr:哈哈,你是對的:) – Stephan202

0

試試看

formatLines = unwords