Part 1 - The Reader

Problem 2

Specs: https://inst.eecs.berkeley.edu/~cs61a/su19/proj/scheme/#problem-2-3-pt

scheme_read:

  • If the current token is the string "nil", return the nil object.

  • If the current token is (, the expression is a pair or list. Call read_tail on the rest of src and return its result.

  • If the current token is ', `, or , the rest of the buffer should be processed as a quote, quasiquote, or unquote expression, respectively. You don't have to worry about this until Problem 7.

  • If the next token is not a delimiter, then it must be a primitive expression. Return it. (provided)

  • If none of the above cases apply, raise an error. (provided)

read_tail:

  • If there are no more tokens, then the list is missing a close parenthesis and we should raise an error. (provided)

  • If the token is ), then we've reached the end of the list or pair. Remove this token from the buffer and return the nil object.

  • If none of the above cases apply, the next token is the operator in a combination, e.g. src contains + 2 3). To parse this:

    1. Read the next complete expression in the buffer. (Hint: Which function can we use to read a complete expression and remove it from the buffer?)

    2. Read the rest of the combination until the matching closing parenthesis. (Hint: Which function can we use to read the rest of a list and remove it from the buffer?)

    3. Return the results as a Pair instance, where the first element is the next complete expression and the second element is the rest of the combination.

Solution:

edit scheme_read,adding:

if val == 'nil':
    # BEGIN PROBLEM 2
    "*** YOUR CODE HERE ***"
    return nil
    # END PROBLEM 2
elif val == '(':
    # BEGIN PROBLEM 2
    "*** YOUR CODE HERE ***"
    return read_tail(src)
    # END PROBLEM 2

edit read_tail, adding:

elif src.current() == ')':
    # BEGIN PROBLEM 2
    "*** YOUR CODE HERE ***"
    src.remove_front()
    return nil
    # END PROBLEM 2
else:
    # BEGIN PROBLEM 2
    "*** YOUR CODE HERE ***"
    first = scheme_read(src)
    rest = read_tail(src)

    return Pair(first, rest)

    # END PROBLEM 2

Last updated