How to use a list of lenses?

Can I use the Traversal list? The following code:

f::[Int] -> [[Int]] fl = [l & i .~ 1 | i<-[ix 0], (l^? i) == Just 0] 

creates an error:

  β€’ Couldn't match type 'Const (Data.Monoid.First Int) [Int]' with 'Identity [Int]' Expected type: ASetter [Int] [Int] Int Integer Actual type: Getting (Data.Monoid.First Int) [Int] Int β€’ In the first argument of '(.~)', namely 'i' In the second argument of '(&)', namely 'i .~ 1' In the expression: l & i .~ 1 

Looking at this question, It seems to me that I need to somehow explicitly specify the type i, but each attempt does not work.

+5
source share
1 answer

The problem is not to explicitly indicate the type. Every time you want to have a lens container or a bypass (the inside of the lens, the lens inside the list, the lens inside Maybe ), you need to use ReifiedLens .

See this question for an explanation:

Why do we need Control.Lens.Reified?

So your example should be written as follows:

 import Control.Lens f :: [Int] -> [[Int]] fl = [ l & i .~ 1 | Traversal i <- [Traversal $ ix 0] , l ^? i == Just 0 ] 

Note that here Traversal is a constructor of the ReifiedTraversal type.

And it works as follows:

 ghci> f [0,0,0] [[1,0,0]] 
+3
source

Source: https://habr.com/ru/post/1273127/


All Articles