I'm writing an AST library for a simple "dynamically typed" language. I have written my syntax tree and parser. Now I'm working on manipulating the AST, and I am interested in using the lens package for that purpose.
Consider
data Obj = Obj !(Map Text Obj)
| Arr ![Obj]
I can write a lens to manipulate object fields pretty easily:
field t (Obj m) = m^.at t
field _ _ = Nothing
but I have no idea where to start for manipulating Arr elements. I'd like a lens along the lines of:
arrIx :: Int -> Obj -> Maybe Obj
arrIx i (Arr objs) = objs^.someLensHere i
where someLensHere i = undefined
I will change my Obj representation for expedience, but it would still be helpful to know how to index on lists using lens.
To index lists using lens, use ix. Example:
>>> 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]
There is also another question about the Difference between at and ix.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With