Search code examples
functional-programminglambda-calculuscons

Show that term `cons` works by showing all beta reductions


I'm new to functional programming.

So the terms cons appends an element to the front of the list. Where

cons ≜ λx:λl:λc:λn: c x (l c n)

How should I go about proving that cons works correctly using beta reduction for a sample function call? For example reducing cons 3 [2,1] to [3,2,1]?

Is there a formula like for the arithmetic operations in lambda calculus? I'm a bit confused on how to approach this compared to an arithmetic operation (i.e. addition or multiplication).

Thanks.


Solution

  • cons ≜ λx:λl:λc:λn: c x (l c n) means that

    cons x l c n =
       c x (l c n)
    

    (in functional / applicative / combinatory notation). So

    cons 3 [2,1] c n = 
     = c 3 ([2,1] c n)
    

    and what is [2,1] if not just shortcut notation for cons 2 [1] so that we continue

     = c 3 (cons 2 [1] c n)
     = c 3 (c    2 ([1] c n))
     = c 3 (c    2 (cons 1 [] c n))
     = c 3 (c    2 (c    1 ([] c n)))
    

    So there's no reduction from cons 3 [2,1] to [3,2,1]; [3,2,1] is cons 3 [2,1]. And [2,1] is cons 2 [1], and [1] is cons 1 [].

    The list cons x xs, when supplied with c and n arguments, will turn into c x (xs c n), and so will xs, in its turn; so any list's elements are used in the chain of applications of c on top one another.

    And what should [] c n turn into? It has nothing in it to put through the c applications -- those are to be applied to a list's elements, and [] has none. So the only reasonable thing to do (and I'm sure you're already given that definition) is to turn [] c n into just n:

    cons 3 [2,1] c n = 
     = c 3 (c    2 (c    1 ([] c n)))
     = c 3 (c    2 (c    1       n ))
    

    whatever c and n are.

    And that's that.