CS 61A

Structure and Interpretation of Computer Programs, Fall 2014

Instructor: John DeNero




Question | Tuple Replace

Define tuple_replace, which takes a tuple tup and a number n, and returns a function with input function fn that replaces the elements n to len(tup) - 1 with those same elements, now applied with fn. If n does not exist in the tuple, return the tuple unchanged.

def tuple_replace(tup, n):
    """
    >>> orig_tup = (2,4,6,8)
    >>> add_four = lambda x : x + 4
    >>> tuple_replace(orig_tup, 2)(add_four)
    (2, 4, 10, 12)
    >>> tuple_replace(orig_tup, 5)(lambda x : x * x)
    (2, 4, 6, 8)
    """
    ## YOUR CODE HERE ##
def tuple_replace(tup, n):
    def gen(fn):
        count, result, apply = 0, (), False
        while count < len(tup):
            if count == n:
                apply = True
            if apply:
                result += (fn(tup[count]),)
            else:
                result += (tup[count],)
            count += 1
        return result
    return gen