Skip to content

Problem 1: Pair Abstraction (150pts)

Problem

Define function pair which takes in two elements and returns a function that works as a pair. You will use functions fst and snd to retrieve the values.

定义一个函数 pair,它接受两个元素并返回一个用数对实现的数学函数。您将使用函数 fstsnd 来检索这些值。

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 pair and two selectors fst and snd, now lets use the abstraction to define two functions change_fst and change_snd that modify the pair.

既然我们已经定义了一个由构造函数 pair 和两个选择函数 fstsnd 组成的抽象,现在让我们使用这个抽象来定义两个修改这个对(pair)的函数 change_fstchange_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_fstchange_snd 中使用有关列表的性质。你可以用 pairfstsnd 函数来解决这个问题。

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)