4

我的数据结构或多或少看起来像这样(为了问题而简化)

data GameObject = GameObject { _num :: Int }
data Game = Game { _objects :: [GameObject] }

我用来makeLenses为这两个生成访问器。因此,我能够像这样进行大规模操作:

-- loop :: MonadState with Game inside
loop = objects.traversed.num += 1

这很棒。


但是,我找不到等效的方法(打印 every num):

game <- get
let objects = _objects game
let objectNums = map _num objects
mapM_ print objectNums

我尝试过类似的东西

uses (objects.traversed.num) >>= mapM_ print

但我看到使用traversed类似状态的唯一方法涉及使用类半群,我不想组合这些字段;我想对驻留在我的 state 中的某个序列中的元素中的每个元素的一部分运行一元操作

那么,这是否可以使用一些提供的镜头功能,或者我必须自己写,不知何故?

4

2 回答 2

6

关于什么

mapMOf_ (objects . traversed . num) print

或者,如果您想将其应用于状态单子的状态,

get >>= mapMOf_ (objects . traversed . num) print

? (也许有一种更像镜头的方式将第一行与状态单子的状态结合起来。如果是这样,我想自己了解一下。)

于 2014-02-24T19:44:04.787 回答
0

此解决方案对镜头查看的状态执行操作

objects . traverse . num .=>> putStrLn . ("num: " ++) . show

例子:

{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}

module Main where

import Control.Monad.IO.Class
import Control.Lens
--       (Getting, Lens', LensLike', lens, makeLenses, view, zoom)
import Control.Lens.Internal.Zoom -- (Focusing)
import Control.Monad.Trans.State.Lazy -- (StateT(StateT), execStateT)

viewM :: Monad m => Getting t s t -> (t -> m a) -> StateT s m a
viewM g f = StateT $ \s -> (, s) <$> f (view g s)

viewEachM ::
     Monad m => LensLike' (Focusing m c) t s -> (s -> m c) -> StateT t m c
viewEachM g f = zoom g $ id .=> f

infix 4 .=>, .=>>

(.=>) :: Monad m => Getting t s t -> (t -> m a) -> StateT s m a
g .=> f = viewM g f

(.=>>) :: Monad m => LensLike' (Focusing m c) t s -> (s -> m c) -> StateT t m c
g .=>> f = viewEachM g f

data GameObject = GameObject
  { _num :: Int
  } deriving (Show)

data Game = Game
  { _objects :: [GameObject]
  } deriving (Show)

makeLenses ''Game

makeLenses ''GameObject

defaultGame = Game {_objects = map GameObject [0 .. 3]}

action :: StateT Game IO ()
action = do
  id .=> putStrLn . ("game: " ++) . show
  objects .=> putStrLn . ("objects: " ++) . show
  objects .=> putStrLn . ("length of objects: " ++) . show . length
  -- use .=>> as alternative
  objects .=>> putStrLn . ("length of objects: " ++) . show . length
  -- if you use traverse you have to use .=>>
  objects . traverse . num .=>> putStrLn . ("num: " ++) . show

main :: IO ()
main = do
  execStateT action defaultGame
  return ()

输出:

game: Game {_objects = [GameObject {_num = 0},GameObject {_num = 1},GameObject {_num = 2},GameObject {_num = 3}]}
objects: [GameObject {_num = 0},GameObject {_num = 1},GameObject {_num = 2},GameObject {_num = 3}]
length of objects: 4
length of objects: 4
num: 0
num: 1
num: 2
num: 3

解析器: lts-9.3

  • 镜头 4.15.4
  • 变压器 0.5
于 2017-09-07T18:09:06.760 回答