haskell - 使用镜头测试 map 成员资格

标签 haskell haskell-lens

使用镜头检查有状态 map 是否有 key 的惯用方法是什么?这是我目前的尝试:

module Foo where

import Control.Lens
import Data.Map
import Control.Monad.State
import Data.Maybe (isJust)

check :: Int -> StateT (Map Int Int) IO ()
check k = do
  present <- use $ at k.to isJust
  unless present $ lift $ putStrLn "Not present!"

这行得通,但是 to isJust 部分感觉有点笨拙...

最佳答案

对于这种特殊情况,请保持简单并且不要使用 lens:

present <- gets (member k)

如果你无论如何都要使用 lens,例如需要通过一些字段遍历到state中才能得到map,使用uses:

present <- uses (field1.field2) (member k)

要根据uses 编写第一个 Action ,请使用标识光学id:

present <- uses id (member k)

但我不建议无缘无故地这样做。

关于haskell - 使用镜头测试 map 成员资格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62204759/

相关文章:

haskell - 删除特定类别窗口的边框

haskell - 如何创建另一个类型类的类型类实例

haskell - 在 Haskell 中模拟交互的有状态对象

haskell - 混合 MonadIO、MonadState 和缩放时出现 "Could not deduce"错误

haskell - 使用 makeClassy 制作具有相同字段名称的镜头 (TH)

haskell - 有条件地修改镜头的目标

haskell - 压缩遍历

windows - ld : too many sections (90295)

haskell - 如何解决 cabal 存储库中不再存在的旧软件包?

haskell - 类型类 101 : GHC too "eager" to derive instance?