使用“镜头”从地图中获取多个结果

时间:2013-06-17 09:28:12

标签: haskell lenses lens

进行这些导入:

> import Control.Lens
Control.Lens> import qualified Data.Map as Map

和地图值定义如下:

Control.Lens Map> let m = Map.fromList [('a', 1), ('c', 3), ('b', 2)]

我可以像这样一个接一个地获取它的元素:

Control.Lens Map> view (at 'b') m
Just 2

我想知道的是,有一组这样的键:

Control.Lens Map> import qualified Data.Set as Set
Control.Lens Map Set> let keys = Set.fromList ['d', 'c', 'b']

如何构建这样一个getter(我猜),使用它我将能够获得匹配元素的集合(或列表):

Control.Lens Map Set> view (**???**) m
[3, 2]

请注意,结果只包含2个元素,因为键'd'不匹配。

2 个答案:

答案 0 :(得分:21)

如果您只想要多个字段的getter,以下内容将起作用。

首先,您需要将镜头中的Accessor设为Monoid实例(该实例位于HEAD中的,但尚未发布 已在lens >= 4中定义 ,所以如果你正在使用旧版本的库,你只需要定义实例。

import Data.Monoid
import Control.Lens

instance Monoid r => Monoid (Accessor r a) where
  mempty = Accessor mempty
  mappend (Accessor a) (Accessor b) = Accessor $ a <> b

然后,您可以使用该实例将多个镜头/遍历组合成一次遍历:

>>> import qualified Data.Set as S
>>> import qualified Data.Map as M
>>> import Data.Foldable (foldMap)
>>> import Control.Lens
>>> let m = M.fromList [('a',1), ('b',2), ('c',3)]
>>> let k = S.fromList ['b','c','e']
>>> m ^.. foldMap at k
[Just 2,Just 3,Nothing]
>>> m ^.. foldMap ix k
[2,3]

foldMap对Accessor使用Monoid实例,为函数使用Monoid实例。

答案 1 :(得分:5)

我认为这是解决方案:

import Control.Applicative
import Control.Lens
import qualified Data.Map as M
import Data.Monoid hiding ((<>))

empty :: (Applicative f, Monoid a) => (b -> f b) -> (a -> f a)
empty _ _ = pure mempty

(<>)
    :: (Applicative f, Monoid a)
    => ((b -> f b) -> (a -> f a))
    -> ((b -> f b) -> (a -> f a))
    -> ((b -> f b) -> (a -> f a))
(l1 <> l2) f a = mappend <$> (l1 f a) <*> (l2 f a)

示例:

>>> toListOf (at "A" <> at "B" <> at "C") (M.fromList [("A", 1), ("B", 2)])
[Just 1, Just 2, Nothing]

这个想法是Traversal是一个幺半群。正确的解决方案需要对Traversal进行新类型化。

编辑:这是包含所有新类型恶作剧的正确Monoid实例:

import Control.Applicative
import Control.Lens
import qualified Data.Map as M
import Data.Monoid
import Data.Foldable

newtype Combinable f a b = Combinable { useAll :: (b -> f b) -> (a -> f a) }

instance (Applicative f, Monoid a) => Monoid (Combinable f a b) where
    mempty = Combinable (\_ _ -> pure mempty)
    mappend (Combinable l1) (Combinable l2)
        = Combinable (\f a -> mappend <$> (l1 f a) <*> (l2 f a))

myMap :: M.Map String Int
myMap = M.fromList [("A", 1), ("B", 2)]

myLens :: Traversal' (M.Map String Int) (Maybe Int)
myLens = useAll $ foldMap (Combinable . at) ["A", "B", "C"]

示例:

>>> toListOf myLens myMap
[Just 1,Just 2, Nothing]