Functions Everywhere

Chris recently got addicted to functions and he presents his best implementation of functions to you:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
function list_of_size(n) {
    function term(x) {
        return x * (x + 1);
    }
    function list_helper(count) {
        if (count > n) {
            return function(f) {
                return -1;
            };
        } else {
            return function(f) {
                return f(term(count), list_helper(count + 1));
            };
        }
    }

    return list_helper(1);
}

function head(f) {
    return f(function (p, q) { return p; });
}

function tail(f) {
    return f(function (p, q) { return q; });
}

function sum(list) {
    if (head(list) === -1) {
        return 0;
    } else {
        return head(list) + sum(tail(list));
    }
}

What is the value of sum(list_of_size(3)) ?

8 20 36

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

1 solution

The function list_of_size returns a function which essentially encodes a linked list in some sense.

The r r th term of this list consists of r ( r + 1 ) r (r+1)

So, we want r = 1 3 r ( r + 1 ) = 20 \sum^3_{r=1} r(r+1) = 20

This implementation of a linked list is essentially like the idea of lists in lambda calculus

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...