如何使用镜头清单?
How to use a list of lens?
我可以使用遍历列表吗?以下代码:
f::[Int] -> [[Int]]
f l = [l & i .~ 1 | i<-[ix 0], (l^? i) == Just 0]
产生错误:
• 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
查看 我想我需要以某种方式明确地为 i 指定类型,但我的每次尝试都失败了。
问题不在于明确指定类型。每次你想要一个镜头或遍历容器(镜头在对内,镜头在列表内,镜头在 Maybe
内)你需要使用 ReifiedLens
.
请参阅此问题以获取解释:
Why do we need Control.Lens.Reified?
所以你的例子应该这样写:
import Control.Lens
f :: [Int] -> [[Int]]
f l = [ l & i .~ 1
| Traversal i <- [Traversal $ ix 0]
, l ^? i == Just 0
]
Note that here Traversal
is a constructor of type ReifiedTraversal
.
它是这样工作的:
ghci> f [0,0,0]
[[1,0,0]]
我可以使用遍历列表吗?以下代码:
f::[Int] -> [[Int]]
f l = [l & i .~ 1 | i<-[ix 0], (l^? i) == Just 0]
产生错误:
• 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
查看
问题不在于明确指定类型。每次你想要一个镜头或遍历容器(镜头在对内,镜头在列表内,镜头在 Maybe
内)你需要使用 ReifiedLens
.
请参阅此问题以获取解释:
Why do we need Control.Lens.Reified?
所以你的例子应该这样写:
import Control.Lens
f :: [Int] -> [[Int]]
f l = [ l & i .~ 1
| Traversal i <- [Traversal $ ix 0]
, l ^? i == Just 0
]
Note that here
Traversal
is a constructor of typeReifiedTraversal
.
它是这样工作的:
ghci> f [0,0,0]
[[1,0,0]]