简体   繁体   中英

Haskell do syntax and I/O

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM