我可以在Show中使用表格和换行符之类的特殊字符吗? [英] Can I use special characters like tabulations and newlines in Show?
问题描述
data Pair = P Int Int
instance Show Pair where
show (P n1 n2) = (show n1) ++ "\t" ++ (show n2)
结果:
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.
[1 of 1] Compiling Main ( labn.hs, interpreted )
Ok, modules loaded: Main.
*Main> show (P 5 6)
"5\t6"
好了,这可能是一个人为的问题,但是我的实际用例是尝试漂亮地打印一棵树-在其中换行符和选项卡似乎有助于可读性.
OK for a pair of ints this might be an artificial problem, but my actual use case is trying to pretty print a tree - where newlines and tabs seem instrumental for readability.
我可以在 show
中以某种方式使用这些字符吗?
Can I somehow use these characters with show
?
推荐答案
show
返回一个字符串,然后将其放在GHCi中时,它会执行 print.显示$(P 5 6)
,它等效于 putStrLn.表演 .显示$(P 5 6)
,它将打印所有字符.
show
returns a string, and then when you put that in GHCi, it does print . show $ (P 5 6)
, which is equivalent to putStrLn . show . show $ (P 5 6)
which will print all the characters.
问题在于双重演出.
您要做的是仅使用打印,如 print(P 5 6)
.如果您使用的是GHCi,则 print
会自动应用于每个表达式,因此您只需要键入
What you want to do is use print only, as print (P 5 6)
. If you're using the GHCi, print
is automatically applied to every expression, so you only need to type
Prelude> P 5 6
这篇关于我可以在Show中使用表格和换行符之类的特殊字符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!