Be-A-Computer: Functional ProgrammingΒΆ

The purpose of these problems is to allow you to test your understanding of functional programming. They should not take more than an hour to complete.

You should do these warm-up exercises by hand. We provide files that will allow you to check your answers.

To get started, run git pull upstream master to make sure you have the latest files. You can check your answers by running the Python program functional.py in pp/bac/

Warm-up exercise #1: What is the output of the following code?

def functional_programming_warmup():
    return map(lambda x: x + 1, 
               filter(lambda x: x % 3 == 0, range(0, 9)))

print("Warmup exercise #1")
l = functional_programming_warmup()
print(list(l))

Warm-up exercise #2: What is the output of the following code?

def mystery2(fn, N):
    def g(x):
        for i in range(N):
            x = fn(x)
        return x
    return lambda y: g(y*2)


print("Warmup exercise #2")
f = mystery2(lambda x: x+1, 10)
print(f(10))

Warm-up exercise #3: What is the output of the following code? (Note: This is a problem from a past CS 121 exam)

def gen_fn(c):
    def fn(x):
        return x % c == 0
    return fn

print("Warmup exercise #3")
print(list(filter(gen_fn(10), map(lambda x: x * 2, [10, 25, -10, 18, -9]))))
print(list(map(lambda x: x * 2, filter(gen_fn(5), [10, 25, -10, 100, -9]))))