HORIZON HASKELLDocslts/ghc-9.14.xd82dee82026-10-12Search names, modules, packages, or :: a typeCtrl K

GHC 9.14.1 · lts/ghc-9.14.x · d82dee8 · 2026-10-12

Modulebyron-spec-ledger-1.1.0.1Haskell2010

Data.AbstractSize

An approach to computing the abstract size of data using TypeRep.

  • 2 types
  • 1 class
  • 1 value
classclass HasTypeReps a where
#

The typeReps function retrieves all the type representations found while traversing the data given as parameter.

CAUTION: for newtypes, do not use 'deriving newtype (HasTypeReps)' to derive instances, rather use 'deriving anyclass (HasTypeReps)'. This is because we use these instances in abstractSize, and for that we prefer to have the newtype wrapper type available for "costing". The difference between newtype and anyclass instances is as follows:

newtype Hash = Hash { unHash :: Int } deriving newtype (..., HasTypeReps) > typeReps someHash = Seq.fromList [Int] vs newtype Hash = Hash { unHash :: Int } deriving stock (...,Generics); deriving anyclass (HasTypeReps) > typeReps someHash = Seq.fromList [Hash, Int]

Examples:

Example1 expression
typeReps "a"fromList [[Char],Char]
Example1 expression
typeReps "ab"fromList [[Char],Char,Char]
Example1 expression
typeReps ([] :: [Int])fromList [[Int]]
Example5 expressions
:set -XDeriveGenericimport GHC.Generics (Generic)data Foo = Foo [Int] (Char, Char) deriving (Generic)instance HasTypeReps FootypeReps $ Foo [1, 2] ('a', 'b')fromList [Foo,[Int],Int,Int,(Char,Char),Char,Char]
Instances54HasTypeReps, …
valueabstractSize :: HasTypeReps a => AccountingMap -> a -> Size
#

abstractSize m a computes the abstract size of a, using the accounting map m. The map m determines the abstract size of each TypeRep contained in a, and this function simply adds all the individual abstract sizes. To be able to extract the type representations (TypeReps) inside a, we require it to be an instance of HasTypeReps.

Examples:

Example3 expressions
:set -XOverloadedListsimport Data.Typeable (typeOf)abstractSize [(typeOf (undefined:: Char), 10)] 'a'10
Example1 expression
abstractSize [(typeOf 'x', 10)] "hello"50
Example1 expression
abstractSize [(typeOf 'x', 10), (typeOf True, 100)] ("hello", False)150
Example1 expression
abstractSize [(typeOf (undefined :: [Int]), 6), (typeOf (1 :: Int), 1)] ([0, 1, 2, 3] :: [Int])10
Example1 expression
abstractSize [(typeOf (undefined :: [Int]), 3), (typeOf (1 :: Int), -1)] ([0, 1, 2] :: [Int])0