Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell do syntax and I/O

Tags:

haskell

ghc

ghci

I was playing around with a simple program in Haskell:

hello :: String -> String
hello s = "Hello, " ++ (trim s) ++ "!\n"

trim :: String -> String
trim [] = []
trim s = head $ words s

main :: IO()
main = do putStr "\nPlease enter your name: "
          name <- getLine
          hstring <- return $ hello name
          putStr hstring

This is the output I am expecting:

Please enter your name: John Doe
Hello, John!

This works as expected when I load the program into ghci. However when I compile the program using

ghc -o hello.exe hello.hs

it starts, waits for input, and then prints both prompts at the same time:

John Doe
Please enter your name: Hello, John!

Why is the behavior different between the interactive environment and compiler, and how can I make the compiler do what I want?

Thanks in advance for the help!

like image 693
astay13 Avatar asked Feb 25 '23 00:02

astay13


1 Answers

This is something of an FAQ. Your lines are being buffered. Use:

import System.IO

main = do
    hSetBuffering stdout NoBuffering
    ...

Also, your code is a bit... unique. For example, you say:

hstring <- return $ hello name
putStr hstring

When you could do:

let hstring = hello name
putStr hstring

or just:

putStr $ hello name
like image 52
Thomas M. DuBuisson Avatar answered Feb 28 '23 13:02

Thomas M. DuBuisson