Generic programming
Advanced page. Read classes and higher-kinded types first; the representation below is a class over a type constructor.
A function written with a class works for many types, but the author of each
type still writes the instance. Generic programming goes one level up: the
compiler can describe a data type’s structure as a value, so a function written
once over that structure works for every type that derives Generic.
This is how the JSON library encodes an arbitrary record without knowing its fields, and how you can write a “count the fields” or “render for debugging” function that needs no per-type instance.
The Generic class
deriving (Generic) gives a type an instance of the class in Moggi.Generics:
class Generic a where
type Rep a :: Type -> Type
from :: a -> Rep a x
to :: Rep a x -> a
Rep a is an associated type (Classes):
each derived instance defines its own representation type. from converts a
value into that representation, and to converts it back. The x parameter is a
phantom that the representation types pass around; it carries no data.
The representation is built from a small set of constructors:
| Representation | Means |
|---|---|
U1 |
a constructor with no fields |
K1 i c |
one field of type c |
f :*: g |
two field groups side by side (a product) |
f :+: g |
a choice between constructors (a sum) |
M1 i c f |
metadata c wrapped around f |
V1 |
no constructors at all |
M1 is tagged with D (the datatype), C (a constructor) or S (a record
selector); the type synonyms D1, C1 and S1 name those three.
A first generic function
A generic function is a class over the representation, plus instances for the representation constructors. Here is a function that counts the fields a constructor carries:
import Moggi.Generics
class GCount f where
gcount :: f p -> Int
instance GCount U1 where
gcount _ = 1
instance GCount (K1 i c) where
gcount _ = 1
instance GCount f => GCount (M1 i c f) where
gcount (M1 x) = gcount x
instance (GCount f, GCount g) => GCount (f :+: g) where
gcount (L1 x) = gcount x
gcount (R1 x) = gcount x
instance (GCount f, GCount g) => GCount (f :*: g) where
gcount (x :*: y) = gcount x + gcount y
size :: (Generic a, GCount (Rep a)) => a -> Int
size x = gcount (from x)
data Shape = Circle Double | Rect Double Double
deriving (Generic)
data Pair a b = Pair a b
deriving (Generic)
main :: IO ()
main = do
putStrLn (show (size (Circle 1.0)))
putStrLn (show (size (Pair 1 True)))
1
2
Read the pieces in order:
gcountis defined on the representation, not on your type. Each instance handles one shape:U1(a nullary constructor) counts one,K1(one field) counts one,M1(metadata) is transparent,:+:adds the alternatives of a sum, and:*:adds the fields of a product.sizeis the bridge. Its context(Generic a, GCount (Rep a))says “whateverRep aturns out to be, it has aGCountinstance”. The compiler solves that at each use, from the representation the derived instance defined.Circle 1.0has one field,Pair 1 Truetwo.Maybe-shaped sums would count the fields of whichever constructor the value uses.
The p in gcount :: f p -> Int is the representation’s phantom parameter. It
never appears in a result, which is why any p will do.
Metadata
The M1 tags are not opaque. Moggi.Generics declares three classes that answer
questions about them, and deriving (Generic) generates the instances:
| Class | Methods answer |
|---|---|
Datatype d |
the type’s name, module, package, whether it is a newtype, whether it is a sum or all-nullary |
Constructor c |
the constructor’s name, whether it is a record, how many fields it has |
Selector s |
the field’s name |
Each method takes a MetaProxy — a value whose only purpose is to carry the
type in its parameter — and returns a String. The names are stored as
promoted strings, so the answers are compile-time constants
(DataKinds).
Using these from your own code means naming a concrete representation type,such as MetaProxy (Rep Color ()) for Color. That is a library-facing facility:
a signature cannot abstract over Rep a
(Polymorphism § Limits), so the library’s codecs read
metadata inside the instances they generate rather than from user code.
Generic in the library: JSON
The clearest production use is JSON. ToJSON and FromJSON have Generic-based
defaults, so a type with Generic gets an encoder and decoder from one
deriving anyclass clause:
import Data.ByteString.Char8 qualified as BS
import Data.JSON
import Moggi.Generics
data Person = Person { name :: String, age :: Int }
deriving (Generic, Show)
deriving anyclass (ToJSON, FromJSON)
main :: IO ()
main = do
result <- eitherDecode (BS.pack "{\"name\":\"Bob\",\"age\":41}")
case result of
Left err -> putStrLn err
Right p -> putStrLn (p.name <> " is " <> show p.age)
Bob is 41
The JSON package is a separate library root. In a checkout, add it (and its
dependency) with --lib:
moggi run app.mog --lib libraries/json/src --lib libraries/containers/src
In a package, declare the dependency and build with moggi build; the
standard library page describes the package layout.
deriving anyclass is what makes this work: it writes an empty instance, and
the class’s default methods do the encoding through Generic. The context
GToJSON (Rep a) is solved at each instance site, exactly as in the GCount
example.
Generic1
Generic1 is the same idea for a type constructor of kind Type -> Type: its
representation marks the parameter position with Par1 and the datatype’s own
recursion with Rec1, and it exposes Rep1, from1 and to1.
deriving (Generic1) abstracts over the declaration’s last type parameter, so
the instance head drops it — data Pair a b derives Generic1 (Pair a):
data Tree a = Leaf a | Node (Tree a) (Tree a)
deriving (Generic1)
leaves :: Tree Int -> Int
leaves t = case from1 t of
M1 (L1 (M1 (M1 (Par1 n)))) -> n
M1 (R1 (M1 (M1 (Rec1 l) :*: M1 (Rec1 r)))) -> leaves l + leaves r
A field may name the parameter as itself (Par1), as the datatype’s own
recursion at it (Rec1, as Tree a does above), or under another type
constructor — Maybe a, [a] — which the representation composes, so a Rose
whose children are a list gets Rec1 List :.: Rec1 Rose:
data Rose a = Rose a (List (Rose a))
deriving (Generic1)
-- type Rep1 Rose =
-- D1 (MetaData "Rose" …) (C1 (MetaCons "Rose" …)
-- (S1 (MetaSel …) Par1 :*: S1 (MetaSel …) (Rec1 List :.: Rec1 Rose)))
The composition is the one form that is not a wrapper: the representation lives
inside the container, so from1 and to1 go through that constructor’s own
map — which Moggi.Generics re-exports, so a derived representation does not
depend on what else the module imports. The head needs a Functor instance
(Functor Maybe, Functor List), which the library provides for the containers
it ships.
A field the parameter does not occur in is a constant (Rec0), which is how
Pair a b gets a Par1 for its last parameter and constants for the ones before
it.
A field that applies a type parameter directly to the abstracted parameter
(f a in Free f a) is Rec1 f: the wrapper holds the field as it is, so no
Functor f is needed. A parameter anywhere else is refused at the declaration:
in a non-final argument of an application it has no position to be mapped into,
and inside a variable-headed application that is not exactly f a (such as
f (Maybe a)) mapping it would need a Functor f the derived instance cannot
name.
A declaration may derive Generic and Generic1 together: the metadata
instances the two representations share are stated once.
Wrappers
Moggi.Generics also declares Generically a and Generically1 f a, newtype
wrappers that exist so a class instance can be routed through a type’s generic
representation. The library ships no instances for them, so they are useful only
once you write the instances your own classes need; they are not a drop-in
deriving mechanism.
Limits
Generic1cannot name aFunctorconstraint. A directf ais represented byRec1 fand needs none; a deeper variable-headed shape such asf (Maybe a)is refused rather than approximated. A parameter under a concrete constructor is represented by composition (above).Genericis stock-only.deriving newtype (Generic)is refused: the representation must be the structure of the declaration, not of its representation type (Deriving).- Metadata cannot name
Rep ain a general signature. Use it from library code, or with a concrete representation type. - No reflection on values. The metadata is compile-time; nothing inspects a value’s type at run time.
Genericcannot be derived for a GADT. A constructor that fixes its index (Lit :: Int -> Expr Int) has no single representation over the parameter, soderiving (Generic)is refused;Eq,Showand the rest still derive (Data types § GADTs).
Where next
- Deriving — the clause that creates the instance.
- Type classes — the mechanism a generic function is built from.
- Higher-kinded types — why
Rep ahas kindType -> Type.