/* Derivative Function with Function Return
   Functional Programming Example -- Higher Order
   H. Conrad Cunningham, Professor
   Computer and Information Science
   University of Mississippi

   Developed for CSci 555, Functional Programming, Spring 2016

1234567890123456789012345678901234567890123456789012345678901234567890

2016-02-10: Developed from 2015 Elixir version

I adapted this derivative module from an Elixir version, which was, in
turn, adapted from a Lua version, which was, in turn, adapted from the
Scheme code in section 1.2.1 of Abelson and Sussman's Structure and
Interpretation of Computer Programs (SICP).

I have only tested this minimally.

Scala and functional programming highlights:
- Takes a function argument
- Returns a function
- Uses anonymous function

*/

object Derivative {

  /* Function "deriv" takes a single-argument function "f" and a small
     delta "dx" and returns a single-argument function (closure) that
     computes an approximation of the value of the derivative at the
     value of its argument.

     Definition of derivative: lim(dx->0) (f(x+dx) - f(x)) / dx
   */

  def deriv(f: Double => Double, dx: Double): Double => Double = 
    ((x: Double) => (f(x+dx) - f(x)) / dx)

  // Should implement extensive tesing externally
  def main(args: Array[String]) {
    def cube(x: Double) = x * x * x
    val dx              = 0.001
    val derivCube       = deriv(cube,dx)
    def actualDerivCube(x: Double) = 3 * x * x 

    println("deriv(cube,dx)(3.0)  = " + deriv(cube,dx)(3.0))
    println("actualDerivCube(3.0) = " + actualDerivCube(3.0))
  }

}
