optics-extra-0.4.2.1: Extra utilities and instances for optics-core
Safe HaskellNone
LanguageHaskell2010

Data.HashMap.Optics

Description

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:

>>> HashMap.fromList [(1, "world")] ^. at 1
Just "world"
>>> HashMap.empty & at 1 .~ Just "world"
fromList [(1,"world")]
>>> 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.

>>> iover imapped const $ HashMap.fromList [(1, "Venus")]
fromList [(1,1)]
>>> ifoldMapOf ifolded (\i _ -> Sum i) $ HashMap.fromList [(2, "Earth"), (3, "Mars")]
Sum {getSum = 5}
>>> itraverseOf_ ifolded (curry print) $ HashMap.fromList [(4, "Jupiter")]
(4,"Jupiter")
>>> 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.

>>> HashMap.fromList [(2, "Earth")] & ix 2 %~ ("New " ++)
fromList [(2,"New Earth")]
>>> preview (ix 8) HashMap.empty
Nothing
Synopsis

Documentation

toMapOf :: (Is k A_Fold, is `HasSingleIndex` i, Eq i, Hashable i) => Optic' k is s a -> s -> HashMap i a Source #

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.

>>> toMapOf ifolded ["hello", "world"]
fromList [(0,"hello"),(1,"world")]
>>> toMapOf (folded % ifolded) [('a',"alpha"),('b', "beta")]
fromList [('a',"alpha"),('b',"beta")]
>>> toMapOf (folded % ifolded) [('a', "hello"), ('b', "world"), ('a', "dummy")]
fromList [('a',"hello"),('b',"world")]

at' :: At m => Index m -> Lens' m (Maybe (IxValue m)) #

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

Example:

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

It also works as expected for other data structures:

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