gaa*_*kam 0 printing string haskell
data Pair = P Int Int
instance Show Pair where
show (P n1 n2) = (show n1) ++ "\t" ++ (show n2)
Run Code Online (Sandbox Code Playgroud)
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"
Run Code Online (Sandbox Code Playgroud)
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?
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.
您想要做的是仅使用print作为print (P 5 6)。如果您使用的是GHCi,print则会自动应用于每个表达式,因此您只需要输入
Prelude> P 5 6
Run Code Online (Sandbox Code Playgroud)