4

As discussed on reddit, you can't just lift a Lens' a b to Lens' (Maybe a) (Maybe b). But for the special case Getter a b, this is obviously possible, since it's isomorphic to a->b. But unlike with Iso, there appears to be no standard function to perform this lift.

What's the preferred way to do that? In cases like

    someFunction $ myMap^.at(i).ꜰᴍᴀᴘGᴇᴛ(mySubGetter)

I could of course do

    someFunction $ myMap^.at(i) & fmap (^.mySubGetter)

but that doesn't work as well in other applications, as when operating on a state monad.

    foo <- use $ myMapInState.at(i).ꜰᴍᴀᴘGᴇᴛ(mySubGetter)
4

1 回答 1

4

我相信你可以用棱镜完成你想要的。

如果您的值具有以下类型:

myMap :: Map String (Int, String)
myMap = mempty

mySubGetter :: Lens' (Int, String) String
mySubGetter = _2

那么你可以这样做:

myVal :: Maybe String
myVal = myMap ^? at "myKey" . _Just . mySubGetter

如果您只想将函数应用于 getter,则可以使用Control.Lens.Getterto中的函数,但您必须手动处理 sublens:

someFunction $ myMap ^. at(i) . to (fmap (^. mySubGetter))
于 2014-10-02T11:42:30.897 回答