Haskell and Control.Lens List

I am writing an AST library for a simple “dynamically typed” language. I wrote my syntax tree and parser. Now I am working on the management of AST, and I am interested in using the lens package for this purpose.

Consider

data Obj = Obj !(Map Text Obj) | Arr ![Obj] 

I can write a lens to easily manipulate objects:

 field t (Obj m) = m^.at t field _ _ = Nothing 

but I don’t know where to start manipulating Arr elements. I need 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 view of Obj for convenience, but it would be useful to know how to index lists using a lens.

+4
source share
1 answer

To index lists with a 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 .

+7
source

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


All Articles