2026-11-14
RoundTrip.hs
escape :: String -> String
escape = concatMap esc
where
esc '\n' = "\\n"
esc c = [c]
unescape :: String -> String
unescape ('\\' : 'n' : rest) = '\n' : unescape rest
unescape ('\\' : '\\' : rest) = '\\' : unescape rest
unescape (c : rest) = c : unescape rest
unescape [] = []
main :: IO ()
main = putStrLn (unescape (escape "C:\\new"))
escape は改行を \ と n の2文字に置き換え、unescape はそれを元に戻すつもりの組です。どんな文字列 s でも unescape (escape s) は s に戻るはずです。ところが s が "C:\\new" のとき、本来は C:\new と1行出るはずが、いまは C: と ew の2行が出ます。
Answer
Wrong
esc '\n' = "\\n"
esc c = [c]
"C:\\new" は C、:、\、n、e、w の6文字で、改行を含みません。いまの escape は改行しか置き換えないので、この文字列をそのまま返します。unescape から見ると、\ と n の並びが、もとから入力にあったものか、改行を置き換えて作ったものかを区別できません。unescape は改行の表記として読み、C:、改行、ew を返します。
Right
esc '\\' = "\\\\"
esc '\n' = "\\n"
esc c = [c]
エスケープに使うバックスラッシュそのものも、2文字の \\ に置き換えます。unescape には '\\' : '\\' を戻す節がすでにあるので、escape の側に足すだけで対になります。これで escape の結果に現れるバックスラッシュは、必ず次の1文字と組になったエスケープの先頭です。"C:\\new" は C:\\new になり、unescape は \\ をバックスラッシュ1文字に戻して、後ろの n を普通の文字として残します。