我如何在Haskell中正确打印换行符? [英] How can I print a newline properly in Haskell?

查看:94
本文介绍了我如何在Haskell中正确打印换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  

我试着制作每月教程的Tic Tac Toe游戏, box :: [String]
box = [0 | 1 | 2,
---------,
3 | 4 | 5,
---------,
6 | 7 | 8]

我在GHCi中得到这个输出:

  [0 | 1 | 2 \\\
, --------- \\\
,3 | 4 | 5 \\\
,--------- \\\
,6 | 7 | 8 \ n ]

我想要:

  0 | 1 | 2 
---------
3 | 4 | 5
---------
6 | 7 | 8

如何以这种方式打印网格?

解决方案

试试类似:

  box = unlines $ [0 | 1 | 2,
---------,
3 | 4 | 5,
---------,





$ b

然后用 putStr

  main = putStr box 

什么 unlines 是取一个字符串列表并使用换行符将它们连接在一起。它基本上将字符串列表视为行列表并将它们转换为单个字符串。



putStr 只是将字符串打印到STDOUT。如果您使用 print 或GHCi查看字符串,则换行符将呈现为 \\\
,而不是实际的换行。发生这种情况是因为 String show 实例设计为按照您输入的字符串序列化字符串,而不是打印它。在输出到STDOUT之前, print 和GHCi都使用 show



如果您处于GHCi提示并想要查看字符串的实际外观,可以直接使用 putStr

  * Main> putStr框
0 | 1 | 2
---------
3 | 4 | 5
---------
6 | 7 | 8
*主页>


I was trying to make Tic Tac Toe game for the monthly tutorial and wrote this code to make a box first:

box :: [String]
box = ["0 | 1 | 2",
       "---------",
       "3 | 4 | 5",
       "---------",
       "6 | 7 | 8"]

I get this output in GHCi:

["0 | 1 | 2\n","---------\n","3 | 4 | 5\n","---------\n","6 | 7 | 8\n"]

I wanted to get:

 0 | 1 | 2
 ---------
 3 | 4 | 5
 ---------
 6 | 7 | 8

How can I print the grid like this?

解决方案

Try something like:

box = unlines $ ["0 | 1 | 2",
                 "---------",
                 "3 | 4 | 5",
                 "---------",
                 "6 | 7 | 8"]

Then output the box using putStr:

main = putStr box

What unlines does is take a list of strings and join them together using newlines. It basically treats the list of strings as a list of lines and turns them into a single string.

putStr just prints the string to STDOUT. If you used print or GHCi to look at the string instead, newlines would be rendered as \n rather than actual newlines. This happens because the show instance of a String is designed to serialize the string as you would have inputted it rather than printing it. Both print and GHCi use show before outputting to STDOUT.

If you are at the GHCi prompt and want to see what the string actually looks like, you can use putStr directly:

*Main> putStr box
0 | 1 | 2
---------
3 | 4 | 5
---------
6 | 7 | 8
*Main>

这篇关于我如何在Haskell中正确打印换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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