Haskell List和Control.Lens

nom*_*men 4 haskell list haskell-lens

我正在为一个简单的"动态类型"语言编写AST库.我编写了语法树和解析器.现在我正在努力操纵AST,我有兴趣为此目的使用镜头包.

考虑

data Obj = Obj !(Map Text Obj)
         | Arr ![Obj]
Run Code Online (Sandbox Code Playgroud)

我可以写一个镜头来很容易地操作对象字段:

field t (Obj m) = m^.at t
field _ _       = Nothing
Run Code Online (Sandbox Code Playgroud)

但我不知道从哪里开始操纵Arr元素.我想要一个镜头:

arrIx :: Int -> Obj -> Maybe Obj
arrIx i (Arr objs) = objs^.someLensHere i 
   where someLensHere i = undefined
Run Code Online (Sandbox Code Playgroud)

我会为了方便而改变我的Obj表示,但知道如何使用镜头对列表进行索引仍然会有所帮助.

ben*_*ofs 7

要使用镜头索引列表,请使用ix.例:

>>> 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]    
Run Code Online (Sandbox Code Playgroud)

关于at和ix之间区别还有另外一个问题.