Problem with "Looping" IO in Haskell

I'm new to Haskell, so I'm trying to create a simple two-player game to help me learn it.

However, I ran into the problem of doing I / O in a "loop". As far as I know, variables set from user input cannot be used unless they are set inside the main one. This is a problem because a recursive call to main is useless to me, since main does not accept any arguments. Ideally, I would have a function called from main, which calls itself until one player loses. But this does not seem to work, since using any variables specified in this function leads to type input errors.

The structure of the program is as follows:

* Request player 1 for the name and set the player1 variable.

* Request player 2 for the name and set the variable player2.

* "loop": alternates between each player, asking for teams until one player loses.

What would be the best way to solve this problem?

+7
source share
2 answers

Ideally, I would get a function called main, which itself calls until one player loses. But this does not seem to work, since any variables set in this function by user input result in an error type.

It is quite possible. Next time, please provide a code so that we can help you with your misunderstanding. Here is an example code snippet:

import System.IO 

To fix buffering problems.

 main = do hSetBuffering stdin NoBuffering putStrLn "Gimma a name ye skervy dog!" name1 <- getLine putStrLn "Good, Good, now another, and make it snappy!" name2 <- getLine loop name1 name2 10 

Note main can call another function ( loop ) that lives in the IO monad. This other function is great for entering and using user input, calling itself and / or accepting arguments.

 loop :: String -> String -> Int -> IO () loop _ _ 0 = return () loop n1 n2 i = do putStrLn $ "Ok Mr. " ++ n1 ++ " and Mrs. " ++ n2 ++ " tis time to roll the dice!" print i putStrLn "Options: (k)eep looping, (i)ncrement loop counter by 10" c <- getChar putStr "\n" case c of 'k' -> loop n1 n2 (i-1) _ -> putStrLn "Blood and bloody ashes, we have to keep going?" >> loop n1 n2 (i+10) 

And the loop just does a simple, stupid job of asking for binary input (incrementing the counter or not) and, well, loops.

If this does not help, perhaps you can post a more detailed question and code. I will edit with an updated answer.

+22
source

Or you can use forever .

 main = do x <- getLine foo forever $ do y <- getLine baz 

If you are new to Haskell, I suggest you go through LYAH for a good introduction.

+6
source

All Articles