Search code examples
haskellhaskell-lens

Setter lens to act on a range of a list in haskell


Given an array eg [1..] is there a way with lenses to double all the numbers in the range [4,100] so it becomes

1,2,3,8,10,12,14,16,...,200,101,102...

I am not very fluent with lenses but I feel like getters are the right tool for this.


Solution

  • > :m + Control.Lens Data.Ix
    > (traverse . filtered (inRange (4, 7)) *~ 2) [1..10]
    [1,2,3,8,10,12,14,8,9,10]
    

    Note that this is probably violating the lens laws, and so may have unexpected behavior in larger code contexts -- one is supposed to be careful that the property passed to filtered is not violated by the updates performed!