Search code examples
haskellioio-monad

Read A String Exactly As It Is in Haskell


My program is something like that:

func = do
      text <- getLine
      return text

If I read line \123\456, the result is, naturally, \\123\\456. How can I obtain \123\456 as the result?


Solution

  • Based on the discussion in comments, it looks like you want to parse the string as if it was a string literal, except that it is not surrounded by quotes.

    We can make use of of read :: Read a => String -> a here that for a string parses it as if it was a string literal to a string. The only problem is that this string literal is surrounded by double quotes (").

    We can thus add these quotes, and work with:

    read ('"' : text ++ "\"") :: String

    Not every string text is however per se a valid string literal, so the above might fail. For example if the text contains a double quote itself, that is not directly preceded by a backslash (\).