我写了一个基本的递归函数:
bibliography_rec :: [(String, String, Int)] -> String
bibliography_rec [] = ""
bibliography_rec (x:xs) = (citeBook x) ++ "\n" ++ (bibliography_rec xs)
Run Code Online (Sandbox Code Playgroud)
citeBook 只需将元组重新格式化为String.
使用此输入运行时:
ghci> bibliography_rec [("Herman Melville", "Moby Dick", 1851),("Georgy Poo", "Alex Janakos", 1666)]
Run Code Online (Sandbox Code Playgroud)
它产生:
"Moby Dick (Herman Melville, 1851)\nAlex Janakos (Georgy Poo, 1666)\n"
Run Code Online (Sandbox Code Playgroud)
我需要逐行打印,所以我使用了这个:
bibliography_rec (x:xs) = putStr ((citeBook x) ++ "\n" ++ (bibliography_rec xs))
Run Code Online (Sandbox Code Playgroud)
我的问题是我的输出需要是StringNOT 类型IO ()
我一直坚持这个问题太久了,所以任何帮助都很棒!
看起来你已经在那里,你只需要putStrLn字符串而不是print它(这是ghci默认做的). print首先运行它的参数show,所以它将引用转义字符,如"\n".
ghci> putStrLn $ bibliography_rec [...]
Run Code Online (Sandbox Code Playgroud)