Why is executing getChar in a terminal different to executing it in GHCi?

haskell

Solution

When you run a program in terminal it uses `LineBuffering` by default, but in `ghci` it is set to `NoBuffering`. You can read about it here. You will have to remove buffering from `stdin` and `stdout` to get the similar behavior.

import Data.Char
import System.IO

main = do
    hSetBuffering stdin NoBuffering
    hSetBuffering stdout NoBuffering
    foo
foo = do
    c <- getChar
    if not $ isUpper c
        then do putChar $ toUpper c
                foo
        else putChar '\n'

Problem

``` import Data.Char main = do c <- getChar if not $ isUpper c then do putChar $ toUpper c main else putChar '\n' ``` Loading and executing in GHCi: ``` λ> :l foo.hs Ok, modules loaded: Main. λ> main ñÑsSjJ44aAtTR λ> ``` This consumes one character at time. But in a terminal: ``` [~ %]> runhaskell foo.hs utar,hkñm-Rjaer UTAR,HKÑM- [~ %]> ``` it consumes one line at time. Why does it behave differently?

Original source