在新行上打印列表元素 [英] Printing elements of a list on new lines
问题描述
printElements :: [String] - > IO()
printElements(x:xs)= print x(某种新行,然后循环?)printElements xs
所以:
[1,2,2,4 ]
会给:
1
2
3
4
在大多数情况下,您不需要在列表上编写循环,它已经完成了。要使用monadic函数遍历列表,您可以使用 mapM (及其 如果您使用 print , show 函数会导致字符串 如果您替换打印 putStrLn ,您将删除转换步骤并直接打印字符串: 现在我想提供另一种解决方案。 Haskell做事的方式尽可能以纯粹的方式进行,只在需要时才使用IO。 所以在这种情况下,我们可以加入所有要用 要加入所有字符串有一个方便的功能: unlines 现在你只需要打印它;注意 unlines 放置了在列表的最后一项之后的新行,所以我们将使用 putStr 而不是 putStrLn I am trying to print the elements of my list onto new lines, but i cant get it to work; So this: would give:
In most cases you don't need to program a loop over a list, it's been done already. To loop over a list with a monadic function, you would use mapM (and its mapM_ variant if you don't care about the result.) If you use print, for print is actually : the show function causes the string If you replace the print by putStrLn, you remove the conversion step and print directly the string: Now I would like to offer another solution. The Haskell way of doing things is doing as much as you can in a pure way, and only use IO when you need it. So in this case we can join all strings to be printed with a To join all the strings there's a handy function : unlines Now you just have to print that; notice that unlines put a newline after the last item of the list, so we'll use putStr instead of putStrLn
这篇关于在新行上打印列表元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
[1,2 ,3,4]
你会得到:
Prelude> mapM_ print [1,2,3,4]
1
2
3
4
前奏>
print :: Show a => a - > IO()
print x = putStrLn(show x)
1
转换为\1 \
, putStrLn 会打印该文件和一个换行符。
Prelude> mapM_ putStrLn [1,2,3,4]
1
2
3
4
Prelude>
\\\
打印字符串,并一次打印所有字符串。
Prelude> unlines [1,2,3,4]
1 \\\
2\\\
3\\\
4\\\
Prelude>
Prelude> putStr(unlines [1,2,3,4])
1
2
3
4
Prelude>
printElements :: [String] -> IO()
printElements (x:xs) = print x (some kind of newline, then loop?) printElements xs
["1","2","2","4"]
1
2
3
4
["1","2","3","4"]
you'd get :Prelude> mapM_ print ["1","2","3","4"]
"1"
"2"
"3"
"4"
Prelude>
print :: Show a => a -> IO ()
print x = putStrLn (show x)
"1"
to be converted to "\"1\""
, putStrLn prints that and a newline.Prelude> mapM_ putStrLn ["1","2","3","4"]
1
2
3
4
Prelude>
\n
, and print all the strings at once.Prelude> unlines ["1","2","3","4"]
"1\n2\n3\n4\n"
Prelude>
Prelude> putStr ( unlines ["1","2","3","4"] )
1
2
3
4
Prelude>