问题
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