在处理名为AppState
的状态时,我想跟踪实例的数量。这些实例具有InstanceId
类型的不同ID。
因此,我的州看起来像这样
import Control.Lens
data AppState = AppState
{ -- ...
, _instanceCounter :: Map InstanceId Integer
}
makeLenses ''AppState
如果之前没有计算具有给定id的实例,那么跟踪计数的函数应该产生1,否则n + 1
:
import Data.Map as Map
import Data.Map (Map)
countInstances :: InstanceId -> State AppState Integer
countInstances instanceId = do
instanceCounter %= incOrSetToOne
fromMaybe (error "This cannot logically happen.")
<$> use (instanceCounter . at instanceId)
where
incOrSetToOne :: Map InstanceId Integer -> Map InstanceId Integer
incOrSetToOne m = case Map.lookup instanceId m of
Just c -> Map.insert instanceId (c + 1) m
Nothing -> Map.insert instanceId 1 m
虽然上面的代码有效,但希望有一种方法可以改进它。我不喜欢的是:
instanceCounter
(首先设置,然后获取值)fromMaybe
始终为Just
,因此我不妨使用fromJust
)incOrSetToOne
中使用镜头进行查找和插入。原因是at
不允许处理lookup
产生Nothing
而是fmap
超过Maybe
的情况。改进建议?
答案 0 :(得分:8)
使用镜头的方法是:
countInstances :: InstanceId -> State AppState Integer
countInstances instanceId = instanceCounter . at instanceId . non 0 <+= 1
这里的关键是使用non
non :: Eq a => a -> Iso' (Maybe a) a
这允许我们将instanceCounter Map中的缺失元素视为0
答案 1 :(得分:4)
一种方法是使用<%=
运算符。它允许您更改目标并返回结果:
import Control.Lens
import qualified Data.Map as M
import Data.Map (Map)
import Control.Monad.State
type InstanceId = Int
data AppState = AppState { _instanceCounter :: Map InstanceId Integer }
deriving Show
makeLenses ''AppState
countInstances :: InstanceId -> State AppState Integer
countInstances instanceId = do
Just i <- instanceCounter . at instanceId <%= Just . maybe 1 (+1)
return i
initialState :: AppState
initialState = AppState $ M.fromList [(1, 100), (3, 200)]
具有逻辑上始终匹配的“部分”模式。
> runState (countInstances 1) initialState
(101,AppState {_instanceCounter = fromList [(1,101),(3,200)]})
> runState (countInstances 2) initialState
(1,AppState {_instanceCounter = fromList [(1,100),(2,1),(3,200)]})
> runState (countInstances 300) initialState
(201,AppState {_instanceCounter = fromList [(1,100),(3,201)]})
答案 2 :(得分:1)
我会用
incOrSetToOne = Map.alter (Just . maybe 1 succ) instanceId
或
incOrSetToOne = Map.alter ((<|> Just 1) . fmap succ) instanceId
我不知道是否有一种透明的方式来做同样的事情。