by noelwelsh · 6y ago · 0 comments
If this "explanation" (scare quotes because it's not really an explanation, just a code dump) doesn't work for you let me know and I can try a different approach.
final case class AD[A](v: A, k: Double => Double) {
// Chain rule
def flatMap[B](f: A => AD[B]): AD[B] = {
val self = this
val next = f(v)
AD(next.v, (d: Double) => next.k(d) * self.k(d))
}
def +(that: AD[Double])(implicit ev: A =:= Double): AD[Double] =
AD(this.v + that.v, (d: Double) => this.k(d) + that.k(d))
def *(that: AD[Double])(implicit ev: A =:= Double): AD[Double] =
AD(this.v * that.v, (d: Double) => (this.k(d) * that.v) + (that.k(d) * this.v))
def sin(implicit ev: A =:= Double): AD[Double] =
this.flatMap(x => AD(Math.sin(x), (d) => Math.cos(x) * d))
def gradient: Double =
this.k(1.0)
}
object AD {
def pure(x: Double): AD[Double] =
AD(x, d => 1.0)
}Shouldn't M actually be a monoid under composition? ie. you should compose like next.k(self.k(d)), not multiply.