CSE 341 Assignment 7 Solution (postscript)
December 7, 1998
1.
Write and test a Miranda function to do symbolic differentiation of arbitrary expressions involving variables, constants, and the operators + - and *. Your function should take two strings as input - the expression and a variable - and return a new string that is an expression representing the derivative of the expression with respect to the variable. I suggest using Scheme syntax for the input and output expressions. (You can use C or Java Syntax if you prefer but it will be much harder to parse the input.)

Your result should be at least minimally simplified, using the following rules:

0 + expr --> expr
expr + 0 --> expr
num + num --> their sum

0 * expr --> 0
expr * 0 --> 0
1 * expr --> expr
expr * 1 --> expr
num * num --> their product

Examples:

   deriv "(+ x 3)"  "x"   =>  "1"
   deriv "(* x y)"  "x"   =>  "y"
   deriv "3"  "x"         =>  "0"
   deriv "(+ (* x 3) (* x 2))"  "x"  =>  "5"
   deriv "(* (* x y) (+ x 3))"  "x"  =>  "(+ (* x y) (* y (+ x 3)))"

Solution 1:
(following the hints)

assign7-hints.m

Solution 2:
(shift/reduce parser)

assign7-shift-reduce.m

Output:

Miranda deriv "(+ x 3)"  "x"
1
Miranda deriv "(* x y)"  "x" 
y
Miranda deriv "3"  "x"
0
Miranda deriv "(+ (* x 3) (* x 2))"  "x"
5
Miranda deriv "(* (* x y) (+ x 3))"  "x"
(+ (* x y) (* y (+ x 3)))
Miranda deriv "(+ 10 hello)" "x"
0
Miranda deriv "(+ 10 hello)" "hello"
1
Miranda deriv "(* catch 22)" "catch"
22
Miranda deriv "(* (+ 5 1) x)" "x"
6



hartline@cs.washington.edu