Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

haskell

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?

like image 814
helq Avatar asked Oct 22 '12 03:10

helq


1 Answers

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'
like image 107
Satvik Avatar answered Nov 16 '22 03:11

Satvik