Using lens pacakge
If we start with the fact that the id function can be used as a lens:
import Control.Lens > [1,2,3,4] ^. id [1,2,3,4]
Then we can move on to how the list can be changed:
> [1,2,3,4] & id %~ (99:) [99,1,2,3,4]
The above allows you to insert at the top of the list. To focus on the last parts of the list, we can use _tail from the Control.Lens.Cons module .
> [1,2,3,4] ^. _tail [2,3,4] > [1,2,3,4] & _tail %~ (99:) [1,99,2,3,4]
Now, to generalize this to the nth position
> :{ let _drop 0 = id _drop n = _tail . _drop (n - 1) :} > [1,2,3,4] ^. _drop 1 [2,3,4] > [1,2,3,4] & _drop 0 %~ (99:) [99,1,2,3,4] > [1,2,3,4] & _drop 1 %~ (99:) [1,99,2,3,4]
The final step is to generalize this to all types using the Cons instance , we can use Cons or <| .
> [1,2,3,4] & _drop 1 %~ (99<|) [1,99,2,3,4] > import Data.Text > :set -XOverloadedStrings > ("h there"::Text) & _drop 1 %~ ('i'<|) "hi there"