我正在为一种简单的“动态类型”语言编写AST库。我已经编写了语法树和解析器。现在我正在处理AST,我感兴趣的是使用镜头包实现这个目的。
考虑一下
data Obj = Obj !(Map Text Obj)
| Arr ![Obj]我可以很容易地写一个镜头来处理物镜:
field t (Obj m) = m^.at t
field _ _ = Nothing但我不知道从哪里开始操作Arr元素。我想要一个这样的镜头:
arrIx :: Int -> Obj -> Maybe Obj
arrIx i (Arr objs) = objs^.someLensHere i
where someLensHere i = undefined为了方便起见,我将改变我的Obj表示,但是知道如何使用镜头在列表上索引仍然是有帮助的。
发布于 2013-09-14 19:22:07
若要使用镜头索引列表,请使用九.。示例:
>>> let myList = [1,4,2,212,5]
>>> myList ^? ix 2 -- (^?) gets the result as a Maybe
Just 2
>>> preview (ix 10) myList -- preview is the non-operator version of (^?)
Nothing
>>> myList & ix 3 .~ 4 -- Set the 4zh element to 4.
[1,4,2,4,5]
>>> myList & ix 10 .~ 5 -- Inserting new elements is not possible
[1,4,2,212,5] 关于at和ix之间的差异还有另外一个问题。
https://stackoverflow.com/questions/18805392
复制相似问题