在新行上打印列表元素 [英] Printing elements of a list on new lines

查看:124
本文介绍了在新行上打印列表元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  printElements 

:: [String] - > IO()
printElements(x:xs)= print x(某种新行,然后循环?)printElements xs

所以:

  [1,2,2,4 ] 

会给:

  1 
2
3
4


在大多数情况下,您不需要在列表上编写循环,它已经完成了。要使用monadic函数遍历列表,您可以使用 mapM (及其

如果您使用 print [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)

show 函数会导致字符串1转换为\1 \ putStrLn 会打印该文件和一个换行符。



如果您替换打印 putStrLn ,您将删除转换步骤并直接打印字符串:

  Prelude> mapM_ putStrLn [1,2,3,4] 
1
2
3
4
Prelude>

现在我想提供另一种解决方案。 Haskell做事的方式尽可能以纯粹的方式进行,只在需要时才使用IO。



所以在这种情况下,我们可以加入所有要用 \\\
打印字符串,并一次打印所有字符串。



要加入所有字符串有一个方便的功能: unlines

  Prelude> unlines [1,2,3,4] 
1 \\\
2\\\
3\\\
4\\\

Prelude>

现在你只需要打印它;注意 unlines 放置了在列表的最后一项之后的新行,所以我们将使用 putStr 而不是 putStrLn

  Prelude> putStr(unlines [1,2,3,4])
1
2
3
4
Prelude>


I am trying to print the elements of my list onto new lines, but i cant get it to work;

printElements :: [String] -> IO()
printElements (x:xs) =  print x (some kind of newline, then loop?) printElements xs

So this:

["1","2","2","4"]

would give:

1
2
3
4

解决方案

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 ["1","2","3","4"] you'd get :

Prelude> mapM_ print ["1","2","3","4"]
"1"
"2"
"3"
"4"
Prelude> 

print is actually :

print :: Show a => a -> IO ()
print x = putStrLn (show x)

the show function causes the string "1" to be converted to "\"1\"", putStrLn prints that and a newline.

If you replace the print by putStrLn, you remove the conversion step and print directly the string:

Prelude> mapM_ putStrLn ["1","2","3","4"]
1
2
3
4
Prelude> 

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 \n, and print all the strings at once.

To join all the strings there's a handy function : unlines

Prelude> unlines ["1","2","3","4"]
"1\n2\n3\n4\n"
Prelude> 

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

Prelude> putStr ( unlines ["1","2","3","4"] )
1
2
3
4
Prelude> 

这篇关于在新行上打印列表元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆