I am trying to make function for computing sum of list elements and length of list in lambda calculus.
Example of a list: a := [1, 2, 3] = λcn.c 1 (c 2 (c 3 n))
sum a
should return 6 and len a
should return 3.
I wrote recursive versions:
len = λl.if (empty l) 0 (plus 1 (len (tail l)))
sum = λl.if (empty l) 0 (plus (head l) (sum (tail l)))
where if, empty, plus, tail are other lamda functions.
Then I did some trick with fixed-point combinator:
len = λl.if (empty l) 0 (plus 1 (len (tail l)))
len = λfl.if (empty l) 0 (plus 1 (f (tail l))) len
len = Y λfl.if (empty l) 0 (plus 1 (f (tail l)))
where Y = λf.(λx.f(x x))(λx.f(x x))
Just the same for sum. So now I have non-recursive versions. But I can't get beta normal form using beta reduction here.
I wonder if there is beta normal forms of these functions and how they look like.
These can be implemented much more easily given that a list is encoded by its own iterator:
means that a list is a function of two arguments: one to use on
cons
nodes and one to use at the end on thenil
constructor.As a consequence you can implement
length
by saying:cons
node and return+1
nil
with0
which translates to:
which would expand to (at each line the expression in bold is being either unfolded or reduced):
Similarly, you can implement
sum
by saying:+
to combine the value stored in acons
and the result of evaluating the tailnil
by0
which translates to:
which would expand to