Problem 1: Pair Abstraction (150pts)
Problem
Define function
pairwhich takes in two elements and returns a function that works as a pair. You will use functionsfstandsndto retrieve the values.
定义一个函数 pair,它接受两个元素并返回一个用数对实现的数学函数。您将使用函数 fst 和 snd 来检索这些值。
def fst(p):
return p(0)
def snd(p):
return p(1)
def pair(x, y):
"""Return a function that represents a pair.
>>> p = pair(1, 2)
>>> fst(p)
1
>>> snd(p)
2
"""
"*** YOUR CODE HERE ***"
Since we have defined an abstraction composed of a constructor
pairand two selectorsfstandsnd, now lets use the abstraction to define two functionschange_fstandchange_sndthat modify the pair.
既然我们已经定义了一个由构造函数 pair 和两个选择函数 fst 和 snd 组成的抽象,现在让我们使用这个抽象来定义两个修改这个对(pair)的函数 change_fst 和 change_snd。
def change_fst(p, v):
"""Change pair p's first element into v and return it.
>>> p = pair(1, 2)
>>> fst(p)
1
>>> snd(p)
2
>>> p = change_fst(p, 3)
>>> fst(p)
3
>>> snd(p)
2
"""
"*** YOUR CODE HERE ***"
def change_snd(p, v):
"""Change pair p's second element into v and return it.
>>> p = pair(1, 2)
>>> fst(p)
1
>>> snd(p)
2
>>> p = change_snd(p, 3)
>>> fst(p)
1
>>> snd(p)
3
"""
"*** YOUR CODE HERE ***"
Hints
Hint: You should never break the abstraction and ruin the world !
-
您绝不能打破抽象并毁掉一切!
-
注意不要在
change_fst和change_snd中使用有关列表的性质。你可以用pair,fst和snd函数来解决这个问题。
Solutions
根据 fst(p) 和 snd(p),写出 pair 函数:
def pair(x, y):
return lambda i: [x, y][i]
或者
def pair(x, y):
return lambda i: x if i == 0 else y
# 或者 return lambda i: y if i else x
注意这里的的 change_xxx 只能用 pair fst snd 这三个函数。
def change_fst(p, v):
return pair(v, snd(p))
def change_snd(p, v):
return pair(fst(p), v)