Spring 2008
*
/ \
* 3
/ \
1 2
1
/ \
2 3
/ \ / \
4 5 6 7
1
/ \
2 3
/ \ /
4 5 6
(You may need to change your tree definition.)
:: in the Scala API.
Note that it is a case class. Look up the definition of
Nil. It is a case object. Scala has a
special construct for classes with a single instance—more about that
in the next lecture. That means you can use these in a match
expression. Write a version of firstN (see the previous lab)
that uses match but not head, tail,
or isEmpty.def simplify(p: Poly) : Poly = p match {
case Prod(f, Const(1.0)) => f
case Sum(f, g) => Sum(simplify(f), simplify(g))
case _ => p
}
What happens when you simplify the derivate of x2 + x with this function?
Prod(Const(1.0),X())?case Sum(f, g) => { val fs = simplify(f) ; val gs = simplify(g) ; if (fs == gs) ... else ... }
(In Scala, == is structural equality, not reference
equality.)
Pow(p, n) where p is a polynomial and
n is an integer. Extend the definition of deriv
to that case class. (Recall that the derivative of pn
is n pn-1 p', where
p' is the derivative of p. What is
simplify(deriv(Pow(X(), 3))?