Search code examples
haskellhaskell-lens

Trouble when composing lenses


First of all, a snippet of code:

λ> let applicationState = ('a','b',(M.fromList $ zip [1..3] [11,22,33],M.fromList $ zip [4,5,6] [44,55,66],M.fromList $ zip [7,8,9] [S.fromList ["77","777","7777"],S.fromList ["88","888","8888"],S.fromList ["99","999","9999"]]))
λ> :t applicationState
applicationState
  :: (Char,
      Char,
      (M.Map Integer Integer,
       M.Map Integer Integer,
       M.Map Integer (S.Set [Char])))
λ> -- this doesn't work
λ> -- applicationState ^. _3 . _3 . at 9 . contains "9999"
λ> -- this does but only for getting, not for setting
λ> applicationState ^. _3 . _3 . at 9 . to (maybe False (S.member "9999"))
True

I was directed by friendly help on the #haskell-lens channel to use that last line, but I also want to be able to set.

Any help?

Later edit: This seems to work:

λ> applicationState ^. _3 . _3 . at 9 . non S.empty . contains "99999"
False
λ> applicationState & _3 . _3 . at 9 . non S.empty . contains "99999" .~ True

Solution

  • The to combinator creates only Getters, and thus you can no longer set. To set, use a prism like _Just in place of the to.