# Lab 02

# Q1: WWPD: Lambda the Free

lambda.py

记住如果觉得有问题就输入 Error 😃

# Q2: WWPD: Higher Order Functions

hof-wwpd.py

# Q3: Lambdas and Currying

def lambda_curry2(func):
    return lambda x: lambda y: func(x, y)
1
2

# Q4: Count van Count

首先返回值是一个函数,所以需要在内部重新定义一个函数用于返回。

def count_cond(condition):
    def count(n):
        i, count = 1, 0
        while i <= n:
            if condition(n, i):
                count += 1
            i += 1
        return count
    return count
1
2
3
4
5
6
7
8
9

# Q5: Both Paths

def both_paths(sofar="S"):
    print(sofar)
    def left():
        return both_paths(sofar+'L')
    def right():
        return both_paths(sofar+'R')
    return left,right
1
2
3
4
5
6
7

# Q8: Composite Identity Function

def composite_identity(f, g):
    return lambda x : f(g(x)) == g(f(x))
1
2

# Q9: I Heard You Liked Functions...

def cycle(f1, f2, f3):
    def ret_fn(n):
        def a(x):
            i = 0
            while (i < n):
                if (i % 3 == 0):
                    x = f1(x)
                elif (i % 3 == 1):
                    x = f2(x)
                elif (i % 3 == 2):
                    x = f3(x)
                i += 1
            return x
        return a
    return ret_fn 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15