18

I've just stumbled upon a thing I don't understand.

If I am using GHCi and use getLine I get the following

Prelude> a <- getLine
Test<Backspace>oo<CR> -- the Backspace action results in a '^?'
Prelude> a
"Test\DELoo"

If I write the same in a Haskell file

module Main where

main :: IO ()
main = do a <- getLine
          putStrLn a

and run the script with runhaskell and enter the same input, the backspace deletes the 't' as expected.

Why is there a difference?

jscs
  • 63,694
  • 13
  • 151
  • 195
epsilonhalbe
  • 15,637
  • 5
  • 46
  • 74

1 Answers1

23

This is due to different buffering behaviour in GHCi and GHC. GHCi has stdin (standard input stream) using NoBuffering by default, and GHC-compiled binaries / runhaskell use LineBuffering by default. If you explicitly do

hSetBuffering stdin NoBuffering

in your Haskell program, you'll be able to reproduce the GHCi behaviour. If you do

hSetBuffering stdin LineBuffering

in GHCi, you'll have lots of unwanted side effects, but can reproduce the runhaskell behaviour.

kosmikus
  • 19,549
  • 3
  • 51
  • 66
  • 2
    you say that I would `have a lot of unwanted side effects`, are they just in ghci unwanted or is there some kind of protection against it in a compiled version - can you elaborate on this a bit more? – epsilonhalbe Jan 14 '14 at 13:14
  • wether you do or not - I'll accept this answer as soon as I can! – epsilonhalbe Jan 14 '14 at 13:14
  • 2
    They're unwanted in GHCi. It will mess with the way that GHCi itself reads inputs, so when you type in stuff for GHCi to run, you'll only see them show up once you hit the Return key. – kosmikus Jan 14 '14 at 13:18
  • So is there a way to delete/revise your input while using `getLine` in GHCi? – jscs Feb 06 '15 at 02:39
  • @JoshCaswell What do you mean? Line-editing such as e.g. `haskeline` provides? – kosmikus Feb 06 '15 at 11:41
  • I'll have a look at that, thanks. My need is probably far more basic: I'm working through the School of Expression book, which used `getLine`, and I ran into this. It's just an annoyance, though, hardly a showstopper. – jscs Feb 06 '15 at 19:35