We mostly use data to store values, like this:
data Sex = Male | Female
data Person = Person {name :: String, age :: Int, sex :: Sex}
charlie :: Person
charlie = Person "Charlie" 32 Male
And now we have nice functions name age and sex to get data values with.
But, with GADTs and Rank2, we can do something cooler:
{-# LANGUAGE GADTs #-}
{-# LANGUAGE Rank2Types #-}
data Sex = Male | Female
data Data a where
Name :: Data String
Age :: Data Int
Sex :: Data Sex
type Person = forall a. Data a -> a
charlie :: Person
charlie Name = "Charlie"
charlie Age = 32
charlie Sex = Male
So, this is pretty darned awesome. It provides us with a gloriously beautiful syntax for defining people, and makes slick use of GADTs.
But is this really any better? How is this represented at runtime? Is pattern-matching actually slower and/or bigger in representation than the data?
lt;dr: How fast is pattern matching compared to data lookup?
If you compile your code with -ddump-asm you can see the pattern match is a series of comparisons and jumps with the data embedded in the instructions (load an address for the string, load a constant for the number 32, etc).
A container, such as a Map or HashMap, will be slower due to the indirection but hopefully it is obvious that a statically named variable is faster than traversing a (potentially dynamic) tree structure.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With