Download The Monad.Reader Issue 11

Transcript
Kenneth Knowles: First-Order Logic à la Carte
Each constructor is parameterized by a type a of subformulae; TT , FF , and
Atom do not have any subformulae so they ignore their parameter. Logical operations such as And have two subformulae. Correspondingly, the And constructor
takes two arguments of type a.
The compound functor Input is now the specification of which constructors may
appear in a first-order logic formula.
type Input = TT ⊕ FF ⊕ Atom
⊕ Not ⊕ Or ⊕ And ⊕ Impl
⊕ Exists ⊕ Forall
The final step is to “tie the knot” with the following Formula data type, which
generates a recursive formula over whatever constructors are present in its functor
argument f .
data Formula f = In{out :: f (Formula f )}
If you have not seen this trick before, that definition may be hard to read and
understand. Consider the types of In and out.
In :: f (Formula f ) → Formula f
out :: Formula f → f (Formula f )
Observe that In ◦ out ≡ out ◦ In ≡ id . This pair of inverses allows us to “roll” and
“unroll” one layer of a formula in order to operate on the outermost constructor.
Haskell does this same thing when you pattern-match against “normal” recursive
data types. Like Haskell, we want to hide this rolling and unrolling. To hide
the rolling, we define some helper constructors, found in Figure 3, that inject a
constructor into an arbitrary supertype, and then apply In to yield a Formula.
To hide the unrolling, we use the fact that a fixpoint of a functor comes with
a fold operation, or catamorphism, which we will use to traverse a formula’s syntax. The function foldFormula takes as a parameter an algebra of the functor
f . Intuitively, algebra tells us how to fold “one layer” of a formula, assuming all
subformulae have already been processed. The fixpoint then provides the recursive
structure of the computation once and for all.
foldFormula :: Functor f ⇒ (f a → a) → Formula f → a
foldFormula algebra = algebra ◦ fmap (foldFormula algebra) ◦ out
We are already reaping some of the benefit of our “à la carte” technique: The
boilerplate Functor instances in Figure 3 are not much larger than the code of
foldFormula would have been, and they are defined modularly! Unlike a monolithic foldFormula implementation, this one function will work no matter which
21