请看下面liftIO
函数中的使用increment
。我有一种预感,使用镜头可以更好地处理它。有什么建议么?
{-# LANGUAGE TemplateHaskell #-}
import Control.Lens
import Control.Monad.IO.Class
import Control.Monad.State
data PersistentCounter = PersistentCounter {
_cValue :: Int,
_cFilename :: FilePath
} deriving Show
makeLenses ''PersistentCounter
increment :: StateT PersistentCounter IO ()
increment = do
t <- cValue <+= 1
f <- use cFilename
liftIO $ writeFile f $ show t
编辑:我认为下面可能有一种类似于“zoom2”的机制。
increment :: StateT PersistentCounter IO ()
increment = do
t <- cValue <+= 1
zoom2 store
store :: PersistentCounter -> IO ()
store counter =
writeFile (counter^.cFilename) $ show (counter^.cValue)
-- | Invoke a function in the inner monad, and pass the state as
-- a parameter.
zoom2 :: Monad m => (s -> m ()) -> StateT s m ()
zoom2 f = get >>= (\s -> lift (f s)) >> return ()