Source: Hutton, Graham. "Programming in Haskell" (p. 180)
- Using
getCh, define an actionreadLine :: IO Stringthat behaves in the same way as getLine, except that it also permits the delete key to be used to remove characters.
Hint: the delete character is
’\ DEL’, and the control character for moving the cursor back one space is’\b’.
I solved this exercise using one '\b' character, but found online that a solver used two. Why the solver of this problem uses "\b \b" instead of "\b" ? Seems like a typo but I am unsure. I have found it works with three '\b' characters.
How does this character work ?
import System.IO
getCh :: IO Char
getCh = do
hSetEcho stdin False
x <- getChar
hSetEcho stdin True
return x
readLine :: IO String
readLine = readLine' ""
readLine' :: String -> IO String
readLine' xs = do
x <- getCh
case x of
'\n' -> do
putChar '\n'
return xs
'\DEL' ->
if null xs
then readLine' ""
else do
putStr "\b \b"
readLine' (init xs)
_ -> do
putChar x
readLine' (xs ++ [x])