Search code examples
haskellhaskell-lens

Lens - What happened to traverseInit?


In early versions Data.List.Lens there was a function traverseInit that was used to manipulate parts of lists. It has been removed, and I assume there is an alternative to this now but I can't quite find it?

how would I do something like

>>> traverseInit +~ 1 $ [1,2,3]
[2,3,3]

Solution

  • traverseInit got replaced with the more general _init :: Snoc s s a a => Traversal' s s from Control.Lens.Cons, so now it works with any sequence-like type which allows access to its right-hand end.

    ghci> [1,2,3] & _init.traverse +~ 1
    [2,3,3]
    

    Note that _init returns a Traversal' s s, not a Traversal' s a, allowing you to replace the whole sublist, possibly changing its length. In the example I had to traverse again to look at the elements. (_init happens to be an affine traversal, meaning it'll never return more than one sublist, but that is not expressible in lens's vocabulary.)

    Control.Lens.Cons includes an analogous traversal of a list's _tail, as well as traversals of a list's _head and _last.