Moggi documentation

Deriving

deriving asks the compiler to write an instance from the shape of the data declaration. It is how show, ==, ordering, enumeration, mapping and JSON codecs arrive without a hand-written instance per type.

data Color = Red | Green | Blue
  deriving (Show, Eq, Ord, Enum, Bounded)

main :: IO ()
main = do
  putStrLn (show Blue)
  putStrLn (show (Red < Green))
  putStrLn (show (succ Red))
  putStrLn (show (minBound :: Color))
Blue
True
Green
Red

Stock deriving

deriving (C) with no strategy is stock: the instance is generated by structural recursion on the declaration. It is the only strategy for most classes.

Class What the derived instance does Requirement
Eq compares constructors, then fields —
Ord constructor order, then field order also derive Eq
Show constructor and field syntax —
Read parses the Show form, at the constructor’s precedence a field’s type needs Read
Enum succ/pred/toEnum/fromEnum across constructors nullary constructors only
Bounded minBound/maxBound are the first and last constructor nullary constructors only
Ix range/index/inRange over the Enum codes of the constructors, or over the fields of one constructor an Enum instance, or one constructor whose fields are Ix
Functor, Foldable, Traversable structure-preserving operations over the last type parameter last parameter only
Generic the representation used by generic programming see Generic programming

Enum and Ix are restricted to enumerations because a value with fields has no position in a sequence to enumerate or index:

Main.mog:3:36: type error: cannot derive Enum: constructor `Pair` has fields (only nullary constructors are allowed)

Ord needs Eq because Ord’s superclass is Eq. Deriving one without the other is an error:

Main.mog:2:13: type error: missing superclass instance: `Eq Age`

Stock Functor requires the parameter to occur only in the last position and only in fields that can be mapped over; a parameter under a function arrow or in a contravariant position is rejected.

Advanced from here. Stock deriving covers most declarations. The rest of this page is about borrowing another type’s instance, routing through a representation, and writing standalone clauses — read it when the stock form is not enough.

newtype deriving

deriving newtype (C) borrows the representation’s instance, re-wrapping arguments and results. It works only on a newtype:

newtype Age = Age Int
  deriving (Show, Eq)
  deriving newtype (Num)

main :: IO ()
main = putStrLn (show (Age 1 + Age 2))
Age 3

The class parameter must appear as a bare type variable in each method’s signature, so Num, Semigroup, Monoid, Eq, Ord and similar work, while a class whose method mentions the parameter under a constructor may not. Functor, Foldable and Traversable are handled separately and may use the f a shape. Generic refuses newtype deriving: its representation must be the declaration’s structure, not its representation type.

Main.mog:2:21: type error: cannot derive newtype `Eq`: not a newtype declaration

via deriving

deriving via (V) C writes instance C V => C T: it dispatches through the instance for V, converting between T and V. The gate is representation compatibility — once both types are unwrapped through their newtype chains, their representations must be equal.

newtype Sum2 = Sum2 Int
  deriving (Eq)

newtype Wrap = Wrap Int
  deriving via (Sum2) Eq

main :: IO ()
main = putStrLn (show (Wrap 1 == Wrap 1))
True

Wrap and Sum2 both unwrap to Int, so the conversion is well defined. A plain data type is its own representation, so a data target is allowed only when some newtype wraps it. Routing through an unrelated representation is rejected:

Main.mog:2:22: type error: via type `Int` is not representationally compatible with target type

Via conversions handle the class parameter at the top level. A method that uses the parameter under a type constructor (Parser a, [a], f a) cannot be converted and is rejected.

anyclass

deriving anyclass (C) writes an empty instance: every method comes from the class’s default. A method with no default gets a body that fails when called, so the instance is complete and only that call fails.

class Describe a where
  describe :: a -> String
  describe _ = "something"

data Foo = Foo
  deriving anyclass (Describe)

main :: IO ()
main = putStrLn (describe Foo)
something

This is the mechanism behind generic JSON codecs: ToJSON and FromJSON have defaults written in terms of Generic, and deriving anyclass instantiates them (Generic programming).

Which strategy runs

deriving (C) picks a strategy in this order:

  1. stock, if one exists for C;
  2. newtype, if the target is a newtype and newtype deriving applies to C;
  3. anyclass otherwise.

Write the strategy explicitly when the answer matters. deriving stock (C), deriving newtype (C), deriving anyclass (C) and deriving via (V) C are always available where the class supports them.

Standalone deriving

An instance may be derived outside the data declaration, which is useful when the type is in another module or when the deriving clause would be crowded:

data Pair a b = Pair a b

deriving instance (Eq a, Eq b) => Eq (Pair a b)

main :: IO ()
main = putStrLn (show (Pair (1 :: Int) True == Pair 1 True))
True

The context you write is used as written for stock deriving; the other strategies add their own constraints (a newtype’s representation contributes its instance constraint, via adds C V, and anyclass adds none). All four are accepted in standalone form: deriving stock instance, deriving newtype instance, deriving anyclass instance and deriving via (V) instance.

Several classes at once

One clause may derive several classes; each is resolved independently, and an explicit strategy may combine with a via type:

data Point = Point { x :: Int, y :: Int }
  deriving (Show, Eq, Ord)

newtype Sum2 = Sum2 Int
  deriving (Eq, Ord)

newtype Total = Total Int
  deriving via (Sum2) (Eq, Ord)

Restrictions

Where next


Moggi compiles to PHP, the JVM and .NET. This site is generated from docs/ in the moggi-lang/moggi repository; the same pages are readable there as Markdown.