Monadic version. ~ (Haskell)

I'm looking for a version .~

that takes a value wrapped in Monad and returns Monad. For example:

(0, 1) & _1 .~ 100 = (100,1)

Hypothetical .~~

:

(0, 1) & _1 .~~ return 100 = return (100,1)

While it won't be easy to define, is it already defined somewhere in the Lens package?

+3


source to share


1 answer


I don't know of any camera operator exactly like this, but with some "tiny" settings, this is essentially what the raw lens application does. Adjustments:

  • You are using a modifying function, not just the parameter value.
  • Yours Monad

    should be Functor

    like almost everything. (This will be required in GHC 7.10, but not quite yet in 7.8.)

So you can do:

Prelude Control.Lens> (0,1) & _1 (const (Just 100))
Just (100,1)
Prelude Control.Lens> (0,1) & _1 (const [100])
[(100,1)]
Prelude Control.Lens> (0,1) & _1 (const [100,200])
[(100,1),(200,1)]

      

Even works with Traversals

:



Prelude Control.Lens> (0,1) & both (const [100,200])
[(100,100),(100,200),(200,100),(200,200)]

      

If you still need an operator, the operator has %%~

been defined, but it is essentially synonymous with the constraint type for id

:

Prelude Control.Lens> (0,1) & _1 %%~ const (return 100) :: Either () (Int,Int)
Right (100,1)

      

Finally, although you said it was simple, your operator .~~

(which I think would logically be .%~

or the like if it were actually in lens

) can be defined as simply

Prelude Control.Lens> let (.~~) = (. const)
Prelude Control.Lens> (0,1) & _1 .~~ return 100 :: Either () (Int,Int)
Right (100,1)

      

+4


source







All Articles