Haskell: Basic Reading Int

The objective is to code the game of Nim in Haskell as a school assignment. I'm new to Haskell and get weird behavior when I try to read input.

The goal is to read two integers. Instead of printing the first message, then prompting and then going on to the second one, it just prints the two messages and I'm unable to give proper input. What is wrong here?

type Board = [Int]      -- The board
type Heap  = Int        -- id of heap
type Turn  = (Int, Int) -- heap and number of stars to remove

readInt :: String -> IO Int
readInt msg = do putStr (msg ++ "> ")
                 inp <- getChar
                 let x = ord inp
                 return x

readTurn :: Board -> IO(Turn)
readTurn b = do heap <- readInt "Select heap:"
                amt <- readInt "Select stars:"
                print heap
                print amt
                return(heap, amt)

Answers


The problem is that stdout is line-buffered by default, which means that nothing gets output until you print a newline. There are two ways to solve this:

  1. Use hFlush stdout after printing the prompt to flush the buffer.
  2. Use hSetBuffering stdout NoBuffering at the start of your program to disable output buffering.

Also, using getChar and ord will read a single character and give you its ASCII value, which is probably not what you wanted. To read and parse a number, use readLn:

import System.IO (hFlush, stdout)

readInt :: String -> IO Int
readInt msg = do
    putStr (msg ++ "> ")
    hFlush stdout
    readLn

Need Your Help

How to deploy Windows 8.0 app on Windows 8.1 tablet?

visual-studio-2012 remote-debugging windows-8.1 windows-rt

I have Windows RT tablet with 8.1 update. I'm trying to build both 8.0 and 8.1 versions of my app. I have no problem deploy my app from Visual Studio 2013 (windows 8.1 version) onto the device. But...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.