Search code examples
haskelllenses

Use Lens as `map`


I want to convert this line of code map (^?! ix 0) [[0, 1], [4, 5], [9, 1]] to entirely use lenses, so something like [[0, 1], [4, 5], [9, 1]] & each . ix 0. However, the types don't match up. What is the correct way to do this?


Solution

  • Use folded:

    Prelude Control.Lens> [[0, 1], [4, 5], [9, 1]] ^.. folded . ix 0
    [0,4,9]
    

    Works on any Foldable.

    Also, if you plan to always extract the first element, perhaps it would be clearer to use the _head traversal from Control.Lens.Cons instead of ix.

    [[0, 1], [4, 5], [9, 1]] ^.. folded . _head