Copyright | (C) Koz Ross 2019 |
---|---|
License | GPL version 3.0 or later |
Stability | Experimental |
Portability | GHC only |
Safe Haskell | Trustworthy |
Language | Haskell2010 |
If a type a
is Finitary
, each inhabitant of a
has an index, which can
be represented as an unsigned integer, spread across one or more machine
words. This unsigned integer will have fixed length (as the number of
inhabitants of a
is finite). We can use this to derive a Unbox
instance, by representing Vector
as a large array of machine words. We
can also derive a Storable
instance similarly.
This is the most efficient encoding of an arbitrary finitary type, both due
to the asymptotics of encoding and decoding (logarithmic in Cardinality a
with base Cardinality Word
) and the fact that word accesses are faster than
byte and bit accesses on almost all architectures. Unless you have concerns
regarding space, this encoding is a good choice.
Unless your type's cardinality is extremely large (a non-trivial multiple of
Cardinality Word
), this encoding is wasteful. If your type's cardinality is
smaller than that of Word
, you should consider Data.Finitary.PackInto
instead, as you will have much larger control over space usage at almost no
performance penalty.
Packing and unpacking between a type and a little-endian array of Word
s
newtype PackWords (a :: Type) Source #
An opaque wrapper around a
, representing each value as a fixed-length
array of machine words.
pattern Packed :: forall (a :: Type). (Finitary a, 1 <= Cardinality a) => a -> PackWords a | To provide (something that resembles a) data constructor for import Data.Finitary.PackWords anInt :: PackWords Int anInt = Packed 10 isPackedEven :: PackWords Int -> Bool isPackedEven (Packed x) = even x Every pattern match, and data constructor call, performs a
\(\Theta(\log_{\texttt{Cardinality Word}}(\texttt{Cardinality a}))\) encoding or decoding of |