Mercoledì 25 ottobre 2017 (90 min)
Rappresentazione simbolica di funzioni
// val f =
// Sub(
// Sum(Prod(X(),X()),
// Prod(Const(2),X()),
// Const(7)
// )
// val g = X()**2 + 2*X() - 7
// println(g(7.5))
// val deriv = g.derivata
sealed
abstract class Fun
{
def apply
(x:
Double):
Double =
this match
{
case Const(i
) => i
case X
() => x
case Sum
(a,b
) => a
(x
)+b
(x
)
}
}
case class Const(x:
Double) extends Fun
case class X
() extends Fun
case class Sum
(a:Fun, b:Fun
) extends Fun
object TestFun
extends App
{
val f = Sum
(X
(),
Const(7))
println
(f
(2.0))
}
Alberi binari
sealed abstract class Albero[T] {
def conta:Int = this match {
case AlberoV() => 0
case AlberoNV(sx,r,dx) => 1+sx.conta+dx.conta
}
}
case class AlberoV[T]() extends Albero[T]
case class AlberoNV[T](sx:Albero[T], r:T, dx:Albero[T]) extends Albero[T]
val v = AlberoNV(AlberoV(), 10, AlberoNV(AlberoV(),20,AlberoV()))
println(v.conta)