Cached maps
All basic map (i.e. those not built up from other maps) in AbstractAlgebra can be cached.
A cache is a dictionary that can be switched on and off at run time that keeps a cache of previous evaluations of the map. This can be useful if the map is extremely difficult to evaluate, e.g. a discrete logarithm map. Rather than evaluate the map afresh each time, the map first looks up the dictionary of previous known values of the map.
To facilitate caching of maps, the Generic module provides a type Generic.MapCache, which can be used to wrap any existing map object with a dictionary.
Importantly, the supertype of the resulting Generic.MapCache object is identical to that of the map being cached. This means that any functions that would accept the original map will also accept the cached version.
Caching of maps only works for maps that correctly abstract access to their fields using accessor functions, as described in the map interface.
Cached map constructors
To construct a cached map from an existing map object, we have the following function:
AbstractAlgebra.cached — Function
cached(M::Map; limit::Int=100, enabled::Bool=true)Return a cached version of the map M, having the same supertype as M, that memoises up to limit values of M in a dictionary. Setting enabled to false creates the map with its cache switched off; it can be switched on later with enable_cache!.
Examples
julia> f = map_from_func(x -> x + 1, ZZ, ZZ);
julia> g = cached(f);
julia> f(ZZ(1)) == g(ZZ(1))
trueConstructing a map with its cache disabled allows the user to quickly go through code and completely disable caches of maps that were previously enabled, for testing purposes, etc.
Caches can also be turned on and off at run time (see below).
Functionality for cached maps
The following functions are provided for cached maps.
AbstractAlgebra.Generic.enable_cache! — Function
enable_cache!(M::Generic.MapCache)Switch the cache of M on. Values stored in the cache while it was disabled are kept.
Examples
julia> f = cached(map_from_func(x -> x + 1, ZZ, ZZ); enabled=false);
julia> enable_cache!(f)
julia> f(ZZ(1))
2AbstractAlgebra.Generic.disable_cache! — Function
disable_cache!(M::Generic.MapCache)Switch the cache of M off, keeping the values it already stores. See enable_cache!.
Examples
julia> f = cached(map_from_func(x -> x + 1, ZZ, ZZ));
julia> disable_cache!(f)
julia> f(ZZ(1))
2AbstractAlgebra.Generic.set_limit! — Function
set_limit!(M::Generic.MapCache, limit::Int)Set the number of further values that may be stored in the cache of M to limit. Setting it to 0 prevents any further values from being cached.
Examples
julia> f = cached(map_from_func(x -> x + 1, ZZ, ZZ));
julia> set_limit!(f, 200)
200