inverseMap f creates a function that is the inverse of a
given function
f. It does so by constructing
Map
internally for each value
f a. The implementation makes sure
that the
Map is constructed only once and then shared for every
call.
Memory usage note: don't inverse functions that have types like
Int as their input. In this case the created
Map will
have huge size.
The complexity of reversed mapping is <math>.
Performance note: make sure to specialize monomorphic type of
your functions that use
inverseMap to avoid
Map
reconstruction.
One of the common
inverseMap use-case is inverting the
show or a
show-like function.
>>> data Color = Red | Green | Blue deriving (Show, Enum, Bounded)
>>> parse = inverseMap show :: String -> Maybe Color
>>> parse "Red"
Just Red
>>> parse "Black"
Nothing
Correctness note: inverseMap expects
injective
function as its argument, i.e. the function must map distinct
arguments to distinct values.
Typical usage of this function looks like this:
data GhcVer
= Ghc802
| Ghc822
| Ghc844
| Ghc865
| Ghc881
deriving (Eq, Ord, Show, Enum, Bounded)
showGhcVer :: GhcVer -> Text
showGhcVer = \case
Ghc802 -> "8.0.2"
Ghc822 -> "8.2.2"
Ghc844 -> "8.4.4"
Ghc865 -> "8.6.5"
Ghc881 -> "8.8.1"
parseGhcVer :: Text -> Maybe GhcVer
parseGhcVer = inverseMap showGhcVer