代码之家  ›  专栏  ›  技术社区  ›  Saurabh Nanda

如何使用镜头修改与条件匹配的元素?

  •  0
  • Saurabh Nanda  · 技术社区  · 6 年前

    我正试着用镜头写一个具有以下类型签名的函数,但是茫然地盯着 filtered 显然不行!

    modifyElem
      :: (a -> Bool)      -- predicate function
      -> (a -> a)         -- modification to apply
      -> [a]
      -> [a]
    

    如果可能的话,还可以进一步概括如下:

    modifyElem
      :: (Foldable t)     -- or (Traversable t)
      -> (a -> Bool)
      -> (a -> a)
      -> t a
      -> t a
    
    1 回复  |  直到 6 年前
        1
  •  3
  •   rampion    6 年前

    试试这个:

    modifyElem :: Traversable t => (a -> Bool) -> (a -> a) -> t a -> t a
    modifyElem predicate transform target =
      target & traverse . filtered predicate %~ transform