Counters are initialized every time?

前端 未结 4 932
独厮守ぢ
独厮守ぢ 2021-01-18 02:17

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

4条回答
  •  情歌与酒
    2021-01-18 02:55

    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'
    

提交回复
热议问题