Search code examples
haskellhaskell-lenslenses

getting a tuple subset with lens over a ReaderT


I would like to play with tuples and lens this way :

myfct :: ReaderT (a,b,c,d,e) m a -> ReaderT (a,c,d) m a
myfct = zoom ...

be able to modify the input tuple to a subset of it...

pseudo code would be something like this :

zoom (_1,_3,_4)

Solution

  • As @dfeuer notes, you probably meant to write:

    myfct' :: Monad m => ReaderT (a,c,d) m a -> ReaderT (a,b,c,d,e) m a
    

    This takes an action that only requires access to the context (a,c,d) and lifts it to an action that can run in a larger context that supplies (a,b,c,d,e). This can be written using magnify like so:

    myfct' = magnify . to $ \(a,_,c,d,_) -> (a,c,d)
    

    On the other hand, if you actually meant what you wrote:

    myfct :: Monad m => ReaderT (a,b,c,d,e) m a -> ReaderT (a,c,d) m a
    

    then you're going to have to explain what this is supposed to do. In particular, if you have an action that accesses the b :: String component:

    action :: Reader (Int,String,Int,Int,Int) Int
    action = asks $ \(_,b,_,_,_) -> length (b :: String)
    

    How do you want to run it in a context with no b :: String?

    test' :: Int
    test' = runReader (myfct action) (1,2,3)