HORIZON HASKELLDocslts/ghc-9.10.x248f8f02026-10-05Search names, modules, packages, or :: a typeCtrl K

GHC 9.10.3 · lts/ghc-9.10.x · 248f8f0 · 2026-10-05

Moduleoptics-extra-0.4.2.1Haskell2010

Data.HashMap.Optics

This module exists to provide documentation for lenses for working with HashMap, which might otherwise be obscured by their genericity.

HashMap is an instance of At and provides at as a lens on values at keys:

Example1 expression
HashMap.fromList [(1, "world")] ^. at 1Just "world"
Example1 expression
HashMap.empty & at 1 .~ Just "world"fromList [(1,"world")]
Example1 expression
HashMap.empty & at 0 .~ Just "hello"fromList [(0,"hello")]

We can traverse, fold over, and map over key-value pairs in a HashMap, thanks to indexed traversals, folds and setters.

Example1 expression
iover imapped const $ HashMap.fromList [(1, "Venus")]fromList [(1,1)]
Example1 expression
ifoldMapOf ifolded (\i _ -> Sum i) $ HashMap.fromList [(2, "Earth"), (3, "Mars")]Sum {getSum = 5}
Example1 expression
itraverseOf_ ifolded (curry print) $ HashMap.fromList [(4, "Jupiter")](4,"Jupiter")
Example1 expression
itoListOf ifolded $ HashMap.fromList [(5, "Saturn")][(5,"Saturn")]

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

Example1 expression
HashMap.fromList [(2, "Earth")] & ix 2 %~ ("New " ++)fromList [(2,"New Earth")]
Example1 expression
preview (ix 8) HashMap.emptyNothing
  • 2 values
valuetoMapOf
  1. :: (Is k A_Fold, HasSingleIndex is i, Eq i, Hashable i)
  2. => Optic' k is s a
  3. -> s
  4. -> HashMap i a
#

Construct a hash map from an IxFold.

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

Example1 expression
toMapOf ifolded ["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 % ifolded) [('a', "hello"), ('b', "world"), ('a', "dummy")]fromList [('a',"hello"),('b',"world")]
valueat' :: At m => Index m -> Lens' m (Maybe (IxValue m))
#

Version of at strict in the value inside the Just constructor.

Example:

Example1 expression
(at () .~ Just (error "oops") $ Nothing) `seq` ()()
Example1 expression
(at' () .~ Just (error "oops") $ Nothing) `seq` ()*** Exception: oops...
Example1 expression
view (at ()) (Just $ error "oops") `seq` ()()
Example1 expression
view (at' ()) (Just $ error "oops") `seq` ()*** Exception: oops...

It also works as expected for other data structures:

Example1 expression
(at 1 .~ Just (error "oops") $ Map.empty) `seq` ()()
Example1 expression
(at' 1 .~ Just (error "oops") $ Map.empty) `seq` ()*** Exception: oops...