How do I print special characters like tabulations or newlines?

[亡魂溺海] 提交于 2019-12-24 10:26:05

问题


[m@green09 ~]$ ghci
GHCi, version 7.6.3: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Prelude> print "asdf"
"asdf"
Prelude> print "\tasdf"
"\tasdf"
Prelude> 

Awesome. Just awesome.

How to print a tabulation or newline?


回答1:


You just do it.

> putStrLn "a\tb"
a   b



回答2:


When you insert a value of type Show a => a into the REPL, the ghci will execute print on it, and if type of this value is IO () it will just evaluate it. If you look at the definition of print you will see that print = putStrLn . show, or less pointfree: print s = putStrLn (show s).

The problem is that show is not a tool for pretty printing. This function's purpose is to "show" the underlying structure, so that it can be read back by Haskell or by human. This is the point where the escaping characters are revealed. You may check that show "\t" /= "\t".

If you want to actually print the string "as it is" you should explicitly call putStr or putStrLn action, that will omit this show layer.


Few examples:

>>> putStrLn "a\tb"
a    b

>>> "a\tb"
"a\tb"

>>> show "a\tb" -- notice that it is actually `putStrLn (show (show "a\tb"))`!
"\"a\\tb\""

>>> print "a\tb"
"a\tb"


来源:https://stackoverflow.com/questions/55105774/how-do-i-print-special-characters-like-tabulations-or-newlines

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!