1.2. A Review of Functional Programming

Before studying logic and proof assistants, we review a few concepts of functional programming using the Haskell language. This chapter has two goals. The first is to recall the style of programming with algebraic data types, pattern matching and higher-order functions, which we will use extensively in Lean. The second is to introduce, still informally, the notion of a type system and its relationship with logic — the idea that types can be read as propositions and programs as proofs. This idea is the common thread running through the whole course.

1.2.1. Haskell

Haskell is a statically typed functional language with non-strict (lazy) evaluation. In this chapter, the first of these features is the one that interests us most.

1.2.1.1. Static typing

Saying that Haskell is statically typed means that every expression has an associated type, determined at compile time. Programs that do not respect types are rejected before they are run. Consider the following definition:

wacky = not '1'

The compiler rejects this code with the message:

• Couldn't match expected type ‘Bool’ with actual type ‘Char’
    • In the expression: not '1'
      In an equation for ‘wacky’: wacky = not '1'
   |
36 | wacky = not '1'
   |         ^^^^^^

The error arises because the function not has type Bool -> Bool, whereas the literal '1' has type Char. Hence not cannot be applied to '1': the type of the argument does not match the type the function expects. The motto of static type systems, coined by Robin Milner, sums up this philosophy: "Well-typed programs cannot go wrong!" — well-typed programs do not commit certain errors at run time.

1.2.1.2. Basic types, lists and tuples

Haskell provides the usual primitive types: Int (with values such as 0, 1, -3), Char (such as 'a' and '1') and floating-point types (Float and Double). From these we can build compound types. Lists are homogeneous sequences of elements:

empty :: [a]
empty = []

oneTwo :: [Int]
oneTwo = [1, 2]

Notice that the type of empty is [a]: the empty list is a list of elements of any type a. Tuples group a fixed number of values, possibly of different types. The degenerate case is the empty tuple (), whose only value is also written ():

p0 :: ()
p0 = ()

p2 :: (Int, Char)
p2 = (0, 'a')

p3 :: (Int, Bool, String)
p3 = (-1, False, "")

1.2.1.3. Functions and data types

Functions are declared by equations, usually preceded by their type signature:

add2 :: Int -> Int
add2 n = n + 2

New types are introduced with the reserved word data, which lists the type's constructors and the arguments of each one. The type below represents pairs, and is parameterized by the types a and b of its components:

data Pair a b = MkPair a b

sample :: Pair Int Bool
sample = MkPair 1 True

1.2.1.4. Higher-order functions

Haskell is a functional language: functions are first-class objects, which can be passed as arguments, returned as results and stored in data structures. The classic example is the function map, which applies a function to each element of a list:

map :: (a -> b) -> [a] -> [b]
map _ [] = []
map f (x : xs) = f x : map f xs

Using map and a partial application of the multiplication operator, we can define a function that doubles every element of a list:

doubleAll :: [Int] -> [Int]
doubleAll = map (* 2)
$> doubleAll [1,2,3]
[2,4,6]

1.2.1.5. Recursive types and pattern matching

Data types can be recursive, that is, constructors may take arguments of the very type being defined. Binary trees are the typical example:

data Tree a
   = Leaf
   | Node a (Tree a) (Tree a)

A tree is either an empty leaf (Leaf) or a node containing a value and two subtrees. The tree whose root is 3, with left child 4 (which in turn has children 3 and 1) and right child 1, and in which the second-level node 3 has children 5 and 2, is represented by:

tree :: Tree Int
tree = Node 3 (Node 4 (Node 3 (Node 5 Leaf Leaf)
                              (Node 2 Leaf Leaf))
                      (Node 1 Leaf Leaf))
              (Node 1 Leaf Leaf)

Functions over recursive types are naturally defined by recursion and pattern matching: there is one equation for each constructor. The height of a tree is zero for a leaf and, for a node, one plus the larger of the heights of its subtrees:

height :: Tree a -> Int
height Leaf = 0
height (Node _ l r) = 1 + max (height l)
                              (height r)

1.2.1.6. Polymorphism and inference

The types of empty, map and height mention type variables (a, b). Haskell supports so-called parametric polymorphism: a single definition works uniformly for any instantiation of these variables. In addition, Haskell compilers perform type inference, which allows us to omit most type annotations: the compiler can deduce, for instance, that height has type Tree a -> Int without the programmer stating it.

1.2.2. Example: a typed interpreter

To consolidate these concepts, we will implement an interpreter for a small language of expressions. The interpreter consists of two components: an algorithm that computes the type of an expression (a type checker) and an algorithm that runs it. Besides exercising Haskell, this example will serve as a basis for understanding how proof assistants such as Lean work: in essence, Lean's kernel is also a type checker, just for a far more expressive language.

1.2.2.1. Syntax

The language under consideration has numbers, Boolean constants, addition, an equality test and conditional expressions. Its grammar is: \begin{array}{lcl} e & \to & n \\ & \mid & \textit{true} \\ & \mid & \textit{false} \\ & \mid & e + e \\ & \mid & e == e \\ & \mid & \textrm{if } e \textrm{ then } e \textrm{ else } e \end{array}

We represent the abstract syntax tree (AST) by a data type with one constructor for each alternative of the grammar:

data Exp
  = ENum Int
  | ETrue | EFalse
  | EAdd Exp Exp
  | EEq Exp Exp
  | EIf Exp Exp Exp

In this representation, the program if 1 == 3 then 2 else 5 is represented by:

ex1 :: Exp
ex1 = EIf (EEq (ENum 1) (ENum 3))
          (ENum 2)
          (ENum 5)

1.2.2.2. Type system

Not every syntactically valid expression is meaningful. Consider the expression true + 2: there is no sensible result for adding a Boolean to a number. To rule out such expressions before running them, we classify them using types. Our language has only two types: \tau \to \textrm{int} \mid \textrm{bool}

represented in Haskell by:

data Ty = INT | BOOL deriving Eq

The type system is defined by inference rules. Each rule has the shape of a fraction: above the line are the premises and below it the conclusion. We read a rule as "if the premises hold, then the conclusion holds". Rules without premises are axioms. Constants have fixed types: \frac{}{n : \textrm{int}} \qquad \frac{}{\textit{true} : \textrm{bool}} \qquad \frac{}{\textit{false} : \textrm{bool}}

Addition requires two integers; equality requires two operands of the same arbitrary type \tau and produces a Boolean: \frac{e_1 : \textrm{int} \quad e_2 : \textrm{int}}{e_1 + e_2 : \textrm{int}} \qquad \frac{e_1 : \tau \quad e_2 : \tau}{e_1 == e_2 : \textrm{bool}}

Finally, the conditional requires the condition to be a Boolean and both branches to have the same type, which becomes the type of the whole expression: \frac{e_1 : \textrm{bool} \quad e_2 : \tau \quad e_3 : \tau}{\textrm{if } e_1 \textrm{ then } e_2 \textrm{ else } e_3 : \tau}

To show that an expression is well typed, we build a derivation: a tree of rule applications whose root is the desired judgment and whose leaves are axioms. For example, the expression if 1 == 3 then 5 else 3 is well typed, as the following derivation attests: \dfrac{\dfrac{\dfrac{}{1 : \textrm{int}} \quad \dfrac{}{3 : \textrm{int}}}{1 == 3 : \textrm{bool}} \quad \dfrac{}{5 : \textrm{int}} \quad \dfrac{}{3 : \textrm{int}}}{\textrm{if } 1 == 3 \textrm{ then } 5 \textrm{ else } 3 : \textrm{int}}

For true + 2, on the other hand, there is no derivation: the only rule whose conclusion has the form e_1 + e_2 : \tau requires \textit{true} : \textrm{int}, which is not derivable.

1.2.2.3. Type checker

The type system above is syntax-directed: for each form of expression there is exactly one applicable rule. This lets us turn it directly into an algorithm. The function tc takes an expression and returns Just t if it has type t, or Nothing if it is ill typed. We use the do notation of the Maybe monad to propagate failures automatically:

tc :: Exp -> Maybe Ty
tc (ENum _) = return INT
tc ETrue    = return BOOL
tc EFalse   = return BOOL
tc (EAdd e1 e2) = do
  t1 <- tc e1
  t2 <- tc e2
  case (t1, t2) of
    (INT, INT) -> return INT
    _ -> fail "type error"
tc (EEq e1 e2) = do
  t1 <- tc e1
  t2 <- tc e2
  if t1 == t2 then return BOOL
  else fail "type error"
tc (EIf e1 e2 e3) = do
  t1 <- tc e1
  t2 <- tc e2
  t3 <- tc e3
  if t1 == BOOL && t2 == t3 then return t2
  else fail "type error"

Notice the direct correspondence between each equation of tc and the corresponding inference rule: the recursive calls check the premises and the final test checks the constraints between the types. In the Maybe monad, fail produces Nothing.

1.2.2.4. Interpreter

To implement the interpreter, we need a type to represent the values (results) of expressions:

data Val = VInt Int | VBool Bool deriving Eq

A few auxiliary functions simplify the definition. Addition only makes sense on integers; comparison, on values of the same kind; and we need to test whether a value is the Boolean true:

addVal :: Val -> Val -> Maybe Val
addVal (VInt n1) (VInt n2) = return $ VInt (n1 + n2)
addVal _ _ = Nothing

eqVal :: Val -> Val -> Maybe Val
eqVal (VInt n1) (VInt n2)   = return $ VBool (n1 == n2)
eqVal (VBool b1) (VBool b2) = return $ VBool (b1 == b2)
eqVal _ _ = Nothing

valTrue :: Val -> Bool
valTrue v = v == VBool True

The interpreter proper recursively evaluates the subexpressions and combines the results:

interp :: Exp -> Maybe Val
interp (ENum n) = return (VInt n)
interp ETrue    = return (VBool True)
interp EFalse   = return (VBool False)
interp (EAdd e1 e2) = do
  v1 <- interp e1
  v2 <- interp e2
  addVal v1 v2
interp (EEq e1 e2) = do
  v1 <- interp e1
  v2 <- interp e2
  eqVal v1 v2
interp (EIf e1 e2 e3) = do
  v1 <- interp e1
  if valTrue v1 then interp e2
  else interp e3

Note that the interpreter still has to deal with failures (Nothing) in the cases where values do not have the expected shape. A fundamental property we expect — and which we will be able to prove once we have the right tools — is type safety: if tc e = Just t, then interp e never fails and produces a value of type t. This is precisely Milner's motto mentioned above. This concludes our first example of an interpreter.

1.2.3. Types and Logic

Haskell's type system is expressive enough to represent simple facts of propositional logic. Intuitively, we can understand polymorphic types built only from variables and the function type constructor -> as formulas of propositional logic built only with implication: type variables play the role of atomic propositions and -> plays the role of \to.

1.2.3.1. An example

The following formula is a tautology of propositional logic: (B \to C) \to (A \to B) \to (A \to C)

It can be proved by the following informal argument:

  • Suppose B \to C and A \to B. Suppose also A.

  • Since A \to B and A, we have B.

  • Since B \to C and B, we have C.

  • Therefore, A \to C.

The key point is that this argument can be represented as a Haskell function. The formula is represented by the type:

comp :: forall a b c. (b -> c) -> (a -> b) -> (a -> c)

and an expression of this type has the same structure as the proof. Let us build it step by step, following the argument:

  1. Assumptions are represented as variables. The assumptions B \to C and A \to B will be the variables bc and ab, and the assumption A will be the variable a:

    comp bc ab a = _
    
  2. Deducing B from A \to B and A corresponds to a function application: ab a.

  3. Likewise, we deduce C from B \to C and B by applying bc:

    comp :: forall a b c. (b -> c) -> (a -> b) -> (a -> c)
    comp bc ab a
       = let
           pb :: b
           pb = ab a
         in bc pb
    

The result is simply function composition! Assumptions correspond to variables (parameters), using an implication (modus ponens) corresponds to function application, and proving an implication corresponds to defining a function. This correspondence, which we will make precise in the coming chapters, is known as the Curry-Howard isomorphism.

In Lean, the same proof can be written in an almost identical way, now treating A, B and C as propositions (elements of Prop):

namespace Ch01 theorem comp {A B C : Prop} : (B → C) → (A → B) → (A → C) := fun bc ab a => let pb : B := ab a bc pb

1.2.3.2. Why not use Haskell for proofs?

In light of the previous example, it is natural to ask: can we then use Haskell to develop programs and proofs about those programs? The answer is no. Expressive as it is, Haskell does not impose the restrictions needed for every program to be interpretable as a proof. In particular, Haskell allows exceptions and non-termination.

With exceptions, we can define a value of any type, and consequently "prove" any formula:

cheat :: forall a. a
cheat = error "Cheating..."

absurd :: forall a b. a -> b
absurd = cheat

The type of absurd corresponds to the formula A \to B, which is certainly not a tautology. The same effect can be achieved with a non-terminating definition:

loop :: forall a . a
loop = loop

To develop proofs without the risk of cheats like these, we must use languages that rule them out. There are currently several proof assistants with expressive type systems that avoid Haskell's problems: there are no arbitrary exceptions, and every function must terminate. In Lean, the attempt to define loop is rejected:

def fail to show termination for Ch01.loop with errors failed to infer structural recursion: Not considering parameter α of Ch01.loop: it is unchanged in the recursive calls no parameters suitable for structural recursion well-founded recursion cannot be used, `Ch01.loop` does not take any (non-fixed) argumentsloop {α : Type} : α := loop
fail to show termination for
  Ch01.loop
with errors
failed to infer structural recursion:
Not considering parameter α of Ch01.loop:
  it is unchanged in the recursive calls
no parameters suitable for structural recursion

well-founded recursion cannot be used, `Ch01.loop` does not take any (non-fixed) arguments
end Ch01

In this course we will use the Lean language to develop proofs. Before that, however, we need a better understanding of the logical side of the correspondence: what exactly is a proof, and which proofs correspond to programs. That is the subject of the next chapter.

1.2.3.3. References

  • LIPOVACA, Miran. Learn You a Haskell for Great Good. No Starch Press, 2011. Available online at learnyouahaskell.com.

  • PIERCE, Benjamin. Types and Programming Languages. MIT Press, 2002.

1.2.4. Exercises

  1. Define in Haskell the functions size :: Tree a -> Int, which counts the number of nodes in a tree, and mirror :: Tree a -> Tree a, which swaps the left and right subtrees of every node.

  2. Define mapTree :: (a -> b) -> Tree a -> Tree b and check that height (mapTree f t) == height t for a few examples. Why do these tests not constitute a proof?

  3. Extend the expression language with multiplication e * e and the logical operator e && e. Write the corresponding typing rules and update tc and interp.

  4. Build the typing derivation for the expression if (1 + 2) == 3 then true else false. Explain why the expression if 1 then 2 else 3 has no derivation.

  5. For each formula below, write a Haskell function whose type represents it (or argue why this is not possible without cheating): (a) A \to A; (b) A \to B \to A; (c) (A \to B \to C) \to (B \to A \to C); (d) A \to B.

  6. Write Lean proofs of formulas (a)–(c) of the previous exercise, in the style of Ch01.comp.