Semantics show wrt escape characters
Consider the following examples ( λ>= ghci, $= shell):
λ> writeFile "d" $ show "d"
$ cat d
"d"
λ> writeFile "d" "d"
$ cat d
d
λ> writeFile "backslash" $ show "\\"
$ cat backslash
"\\"
λ> writeFile "backslash" "\\"
$ cat backslash
\
λ> writeFile "cat" $ show "🐈" -- U+1F408
$ cat cat
"\128008"
λ> writeFile "cat" "🐈"
$ cat cat
🐈
I understand that another way "\128008"is another way of representing
"🐈"in the Haskell source code. My question is: why does the example "🐈"behave like a backslash instead of like "d"? Since this is a printed symbol, should it not behave like a letter?
More generally, what is the rule to determine if a character is displayed as a printable character or as an escape code? I looked at Section 6.3 in the Haskell 2010 Language report, but it does not indicate the exact behavior.
TL: DR; ASCII (0-127) show n . * .
* ( ) ( ).
, !
String = [Char], instance Show Char
.
.
:
-- | @since 2.01
instance Show Char where
showsPrec _ '\'' = showString "'\\''"
showsPrec _ c = showChar '\'' . showLitChar c . showChar '\''
showList cs = showChar '"' . showLitString cs . showChar '"'
, String ( showList)
ShowLitString, Char - ShowLitChar.
.
showLitString :: String -> ShowS
-- | Same as 'showLitChar', but for strings
-- It converts the string to a string using Haskell escape conventions
-- for non-printable characters. Does not add double-quotes around the
-- whole thing; the caller should do that.
-- The main difference from showLitChar (apart from the fact that the
-- argument is a string not a list) is that we must escape double-quotes
showLitString [] s = s
showLitString ('"' : cs) s = showString "\\\"" (showLitString cs s)
showLitString (c : cs) s = showLitChar c (showLitString cs s)
-- [explanatory comments ...]
, ShowLitString
ShowLitChar.
[: ShowS,
, ,
.]
, , ShowLitChar (
, ).
-- | Convert a character to a string using only printable characters,
-- using Haskell source-language escape conventions. For example:
-- [...]
showLitChar :: Char -> ShowS
showLitChar c s | c > '\DEL' = showChar '\\' (protectEsc isDec (shows (ord c)) s)
-- ^ Pattern matched for cat
showLitChar '\DEL' s = showString "\\DEL" s
showLitChar '\\' s = showString "\\\\" s
-- ^ Pattern matched for backslash
showLitChar c s | c >= ' ' = showChar c s
-- ^ Pattern matched for d
-- Some more escape codes
showLitChar '\a' s = showString "\\a" s
-- similarly for '\b', '\f', '\n', '\r', '\t', '\v' etc.
-- showLitChar ... = ...
, . ord c int,
, ASCII (ord '\DEL' == 127).
ASCII
. .
"". ( ) , :
-- | @since 2.01
instance Show Char where
,
. : . .
Bonus
git blame , GHC Github mirror;).
( ).
commit - 15 (!). Unicode.
isPrint c = iswprint (ord c) /= 0
foreign import ccall unsafe "u_iswprint"
iswprint :: Int -> Int
, iswprint,
. 13 .
, ,
? . - GHC ,
:). - , Unicode, (~ 15 ), Unicode .