Counters are initialized every time?

前端 未结 4 936
独厮守ぢ
独厮守ぢ 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:48

    Just like in code outside of IO, you can string together a series of computations using a fold. foldM operates within a monad, e.g.

    main = do
        conn <- connect "192.168.35.62" 8081
        let tryOnePing (c, f) i = do
            p <- ping conn "ping"
            return $ if p == "pong" then (c+1, f) else (c, f+1)
        (c, f) <- foldM tryOnePing (0, 0) [0 .. 10000]
        print (c, f)
    

提交回复
热议问题