如何使用putStrLn在haskell的函数中打印[String]的每个元素?

lkn*_*dhu 1 haskell

我想打印一个字符串列表,如["hallo", "world", "!"]使用putStrLn,以便我得到输出:

hello
world
!
Run Code Online (Sandbox Code Playgroud)

如何使用函数执行此操作?我有

printMe :: [String] -> String
printMe (x:xs) = 
Run Code Online (Sandbox Code Playgroud)

但不知道该怎么做

unp*_*680 9

您可以使用Haskell库的常规工具.此版本返回连接的字符串,以便您在更合适的位置打印出来.

 printMe xs = foldr (++) "" (map (\str -> str ++ "\n") xs)
Run Code Online (Sandbox Code Playgroud)

或者您可以通过更简单的映射立即打印:

 printMeM xs = mapM_ putStrLn xs
Run Code Online (Sandbox Code Playgroud)

这非常粗鲁,因为我还不是真正的Haskell程序员.

  • @progo另一个提示:查找`unlines` :) (3认同)
  • @ Ingo,`intersperse`不会添加最终终止的换行符。@ progo,`mapM_ putStrLn`是惯用的方式,很好的回答:-) (2认同)