You've seen such a prompt very often.
OK? [y/n]
Your cursor is just after the prompt with 1 space. If you type y
the process will continue and if you type any other characters, not only n
, the process will stop. This is easy to implement in Ruby.
print "OK? [y/n] "
if gets.chars.first == 'y'
puts 'go go go'
else
puts 'nooo'
end
It seems to be easy for Haskell beginners to implement it in Haskell like the following code.
main = do putStr "OK? [y/n] "
s <- getLine
case (head s) of
'y' -> putStrLn "Nice"
otherwise -> putStrLn "omg"
But it doesn't work appropriately due to stdout
buffering. Haskell has IO
library that can control buffering. Add hFlush stdout
after importing the library.
import IO (hFlush, stdout)
main = do putStr "OK? [y/n] "
hFlush stdout
s <- getLine
case (head s) of
'y' -> putStrLn "Nice"
otherwise -> putStrLn "omg"
This works.
No comments:
Post a Comment