Can I use special characters like tabulations and newlines in Show?

我是研究僧i 提交于 2020-01-16 17:35:07

问题


data Pair = P Int Int

instance Show Pair where
  show (P n1 n2) = (show n1) ++ "\t" ++ (show n2)

Result:

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.

Can I somehow use these characters with show?


回答1:


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.

The problem is with the double show.

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


来源:https://stackoverflow.com/questions/55105976/can-i-use-special-characters-like-tabulations-and-newlines-in-show

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