CS 6510 Homework 2

Due: Tuesday, January 26th, 2016 11:59pm

Functions that Accept Multiple Arguments

Start with the interpreter with functions, and extend the implementation to support multiple or zero arguments to a function, and multiple or zero arguments in a function call.

For example,

  {define {area w h} {* w h}}

defines a function that takes two arguments, while

  {define {five} 5}

defines a function that takes zero arguments. Similarly,

  {area 3 4}

calls the function area with two arguments, while

  {five}

calls the function five with zero arguments.

Since you must change the ExprC datatype, and since different people may change it in different ways, you must update the parse function, which accepts an S-expression and produces an ExprC value. Also, you must update the parse-fundef function that takes one quoted define form and produces a FunDefC value.

Note: The fact that quoting an identifier produces a symbol instead of an s-exp is inconvenient, because it means that (parse 'x) doesn’t work. You could use (parse (symbol->s-exp 'x)), but a more readable trick is to use a backquote insted of a normal quote: (parse `x). A backquote always produces an s-exp. It also allows an escape back out of quoting, but we don’t need that feature, yet.

At run-time, a new error is now possible: function application with the wrong number of arguments. Your interp function should detect the mismatch and report an error that includes the words “wrong arity”.

Some examples:

  (test (interp (parse '{f 1 2})
                (list (parse-fundef '{define {f x y} {+ x y}})))
        3)
  (test (interp (parse '{+ {f} {f}})
                (list (parse-fundef '{define {f} 5})))
        10)
  (test/exn (interp (parse '{f 1})
                    (list (parse-fundef '{define {f x y} {+ x y}})))
            "wrong arity")

A function would be ill-defined if two of its argument names were the same. To prevent this problem, your parse-fundef function can optionally detect this problem and report a “bad syntax” error. For example, (parse-fundef '{define {f x x} x}) could report a “bad syntax” error, while (parse-fundef '{define {f x y} x}) should produce a FunDefC value.

Remember that plai-typed provides the following useful function:

Practice Exercises

These exercises are not assigned as homework, but you might find them helpful for extra practice.


Last update: Wednesday, January 13th, 2016
mflatt@cs.utah.edu