如果没有ioref,我怎么重构它呢?



我怎样才能重构它,最终使ioref不再是必需的呢?

inc :: IORef Int -> IO ()
inc ref = modifyIORef ref (+1)
main = withSocketsDo $ do
        s <- socket AF_INET Datagram defaultProtocol
        c <- newIORef 0
        f <- newIORef 0
        hostAddr <- inet_addr host
        time $ forM [0 .. 10000] $ i -> do
              sendAllTo s (B.pack  "ping") (SockAddrInet port hostAddr)
              (r, _) <- recvFrom s 1024 
              if (B.unpack r) == "PING" then (inc c) else (inc f)
        c' <- readIORef c
        print (c')
        sClose s
        return()

在这里使用IORefs有什么问题?你在IO里负责网络操作。ioref并不总是最干净的解决方案,但在这种情况下,它们似乎做得很好。

无论如何,为了回答这个问题,让我们删除ioref。这些引用作为保持状态的一种方式,所以我们必须想出另一种方式来保持有状态信息。

我们要做的伪代码是这样的:

open the connection
10000 times: 
  send a message
  receive the response
  (keep track of how many responses are the message "PING")
print how many responses were the message "PING"

1000 times下缩进的块可以抽象成它自己的函数。如果我们要避免ioref,那么这个函数将不得不接受前一个状态并产生下一个状态。

main = withSocketsDo $ do
  s <- socket AF_INET Datagram defaultProtocol
  hostAddr <- inet_addr host
  let sendMsg = sendAllTo s (B.pack  "ping") (SockAddrInet port hostAddr)
      recvMsg = fst `fmap` recvFrom s 1024
  (c,f) <- ???
  print c
  sClose s

那么问题是:我们在???位置放什么?我们需要定义一些方法来"执行"IO操作,获取其结果,并以某种方式修改该结果的状态。我们还需要知道要做多少次。

 performRepeatedlyWithState :: a             -- some state
                            -> IO b          -- some IO action that yields a value
                            -> (a -> b -> a) -- some way to produce a new state
                            -> Int           -- how many times to do it
                            -> IO a          -- the resultant state, as an IO action
 performRepeatedlyWithState s _ _ 0 = return s
 performRepeatedlyWithState someState someAction produceNewState timesToDoIt = do
   actionresult <- someAction
   let newState = produceNewState someState actionResult
   doWithState newState someAction produceNewState (pred timesToDoIt)

我在这里所做的就是写下与我上面所说的相匹配的类型签名,并产生相对明显的实现。我给每个函数取了一个非常冗长的名字,希望能让这个函数的含义更清楚。有了这个简单的功能,我们只需要使用它。

let origState = (0,0)
    action = ???
    mkNewState = ???
    times = 10000
(c,f) <- performRepeatedlyWithState origState action mkNewState times

我在这里填写了简单的参数。初始状态是(c,f) = (0,0),我们要重复10000次。(还是10001?)但是actionmkNewState应该是什么样子呢?action的类型应该是IO b;它是一些IO动作,产生一些

action = sendMsg >> recvMsg

我将sendMsgrecvMsg绑定到前面代码中的表达式。我们想要执行的操作是发送消息,然后接收消息。此操作产生的值是收到的消息。

现在,mkNewState应该是什么样子?它的类型应该是a -> b -> a,其中a是状态类型,b是操作结果类型。

mkNewState (c,f) val = if (B.unpack val) == "PING"
                         then (succ c, f)
                         else (c, succ f)

这不是最干净的解决方案,但你明白大意了吗?您可以通过编写递归调用自身的函数来替换ioref,并传递额外的参数以跟踪状态。同样的想法也体现在针对类似问题提出的解决方案中。

Bang模式,正如Nathan Howell建议的那样,将是明智的,以避免在您的状态中建立大量的succ (succ (succ ...))):

mkNewState (!c, !f) val = ...

基于前面关于堆栈溢出的注释。

在IORef或foldM情况下的累加器'f'和'c'都需要计算,以防止在迭代时分配长链的内存。一种强制评估坦克的方法是使用爆炸模式。这告诉编译器对该值求值,去掉"thunk",即使函数中不需要该值。

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
import Control.Concurrent
import Control.Monad
import Data.ByteString.Char8
import Data.Foldable (foldlM)
import Data.IORef
import Network.Socket hiding (recvFrom)
import Network.Socket.ByteString (recvFrom, sendAllTo)
main = withSocketsDo $ do
  let host = "127.0.0.1"
      port= 9898
  s <- socket AF_INET Datagram defaultProtocol
  hostAddr <- inet_addr host
  -- explicitly mark both accumulators as strict using bang patterns
  let step (!c, !f) i = do
        sendAllTo s "PING" (SockAddrInet port hostAddr)
        (r, _) <- recvFrom s 1024 
        return $ case r of
          -- because c and f are never used, the addition operator below
          -- builds a thunk chain. these can lead to a stack overflow
          -- when the chain is being evalulated by the 'print c' call below.
          "PING" -> (c+1, f)
          _      -> (c, f+1)
  (c, f) <- foldlM step (0, 0) [0..10000]
  print c
  sClose s
  return ()

最新更新