HORIZON HASKELLDocslts/ghc-9.10.xc74966e2026-09-27Search names, modules, packages, or :: a typeCtrl K

GHC 9.10.3 · lts/ghc-9.10.x · c74966e · 2026-09-27

Modulelens-5.3.5Haskell2010

Data.Map.Lens

One of most commonly-asked questions about this package is whether it provides lenses for working with Data.Map.Map. It does, but their uses are perhaps obscured by their genericity. This module exists to provide documentation for them.

Data.Map.Map is an instance of At, so we have a lenses on values at keys:

Example1 expression
Map.fromList [(1, "world")] ^.at 1Just "world"
Example1 expression
at 1 .~ Just "world" $ Map.emptyfromList [(1,"world")]
Example1 expression
at 0 ?~ "hello" $ Map.emptyfromList [(0,"hello")]

We can traverse, fold over, and map over key-value pairs in a Data.Map.Map, thanks to its TraversableWithIndex, FoldableWithIndex, and FunctorWithIndex instances.

Example1 expression
imap const $ Map.fromList [(1, "Venus")]fromList [(1,1)]
Example1 expression
ifoldMap (\i _ -> Sum i) $ Map.fromList [(2, "Earth"), (3, "Mars")]Sum {getSum = 5}
Example1 expression
itraverse_ (curry print) $ Map.fromList [(4, "Jupiter")](4,"Jupiter")
Example1 expression
itoList $ Map.fromList [(5, "Saturn")][(5,"Saturn")]

A related class, Ixed, allows us to use ix to traverse a value at a particular key.

Example1 expression
ix 2 %~ ("New " ++) $ Map.fromList [(2, "Earth")]fromList [(2,"New Earth")]
Example1 expression
preview (ix 8) $ Map.emptyNothing

Additionally, Data.Map.Map has TraverseMin and TraverseMax instances, which let us traverse over the value at the least and greatest keys, respectively.

Example1 expression
preview traverseMin $ Map.fromList [(5, "Saturn"), (6, "Uranus")]Just "Saturn"
Example1 expression
preview traverseMax $ Map.fromList [(5, "Saturn"), (6, "Uranus")]Just "Uranus"
  • 1 value
  • Packagelens-5.3.5
  • Exports1
  • LanguageHaskell2010
  • LicenceBSD-2-Clause
  • SourceLens.hs
valuetoMapOf :: IndexedGetting i (Map i a) s a -> s -> Map i a
#

Construct a map from a IndexedGetter, Control.Lens.Fold.IndexedFold, Control.Lens.Traversal.IndexedTraversal or Control.Lens.Lens.IndexedLens

The construction is left-biased (see Data.Map.Lazy.union), i.e. the first occurrences of keys in the fold or traversal order are preferred.

Example1 expression
toMapOf folded ["hello", "world"]fromList [(0,"hello"),(1,"world")]
Example1 expression
toMapOf (folded . ifolded) [('a',"alpha"),('b', "beta")]fromList [('a',"alpha"),('b',"beta")]
Example1 expression
toMapOf (folded <.> folded) ["foo", "bar"]fromList [((0,0),'f'),((0,1),'o'),((0,2),'o'),((1,0),'b'),((1,1),'a'),((1,2),'r')]
Example1 expression
toMapOf ifolded $ Map.fromList [('a', "hello"), ('b', "world")]fromList [('a',"hello"),('b',"world")]
toMapOf ::          IndexedGetter i s a     -> s -> Map i a
toMapOf :: Ord i => IndexedFold i s a       -> s -> Map i a
toMapOf ::          IndexedLens' i s a      -> s -> Map i a
toMapOf :: Ord i => IndexedTraversal' i s a -> s -> Map i a