I have this code inside a function with side effects ... -> IO()
let index_player = (-1)
dronePositionByPlayer <- replicateM nb_players $ do
let index_player = index_player + 1
dronePositions <- replicateM nb_drones $ do
input_line <- getLine
let input = words input_line
let dx = read (input!!0) :: Int
let dy = read (input!!1) :: Int
let dronePosition = DronePosition (Position dx dy) index_player
hPutStrLn stderr $ "position = " ++ show dronePosition
return (dronePosition)
return (dronePositions)
When I execute it, while parsing the input data (which is several lines containing each an x and y position) I have this trace on the stardard error output:
position = DronePosition (Position 703 892) Answer: <<loop>>
Obviously it can read the first position, but then it goes in infinite-loop, probably trying to display the field index_player.
DronePosition and Position are simple algebraic datatypes:
data Position = Position Int Int deriving Show
data DronePosition = DronePosition Position Drone deriving Show
What is ill-formed in my code ?
let index_player = index_player + 1
The above is a recursive definition, resulting in a index_player variable to be computed by adding one recursively -- forever. That does not terminate. It does not refer to the previous variable of the same name declared a few lines above.
If you want a loop, you can adapt e.g.
xs <- forM [0..100] $ \i -> do
print i
return (1000 + i)
The above prints all the numbers from 0 to 100, and defines xs to be the list of all the returned numbers, i.e. [1000..1100]. Remember to import Control.Monad to use forM.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With