I try to make a simple counter. My counters do not go up however. It seems to me as if they are re-initialized every time by the function \"inc\" or maybe the (n+1) does not
In Haskell data are immutable by default. This means that the c
in inc c
is always zero.
To get mutable variables in Haskell, you have to ask for them explicitly, i.e. by using IORefs. Using them you could write something like:
import Data.IORef
inc :: IORef Int -> IO ()
inc ref = modifyIORef ref (+1)
main :: IO ()
main = do
c <- newIORef 0
f <- newIORef 0
putStrLn "Starting..."
conn <- connect "192.168.35.62" 8081
time $
forM_ [0..10000] $ \i -> do
p <- ping conn "ping"
if p=="pong"
then inc c
else inc f
c' <- readIORef c
printf "Roundtrips %d\n" c'