Search code examples
haskellhaskell-lens

How to snoc using the lens library?


I am stumped again while trying to work with Edwards lens library. I try to snoc something onto the end of a vector in a state context:

data Foo = Foo {
  _vec :: Vector Int
}

makeLenses ''Foo

testCons x = vec <>= singleton x

While this works I'd like to use [cons][2] but I have no idea how. The documentation mentions [0,1,2] |> 3 === [0,1,2,3] but I have no idea how to do this in the state context.


Solution

  • The (%=) combinator lets you apply a function to the target of a Lens; you want something like

    stateSnoc :: MonadState Foo m => Int -> m ()
    stateSnoc x = vec %= (|> x)