--[[ Derivative Function with Function Return Functional Programming Example -- Higher Order H. Conrad Cunningham, Professor Computer and Information Science University of Mississippi Developed for CSci 658, Software Language Engineering, Fall 2013 1234567890123456789012345678901234567890123456789012345678901234567890 2013-09-11: Completed prototype This higher-order differentiation function is adapted from section 1.3.4 of Abelson and Sussman's Structure and Interpretation of Computer Programs (SICP) textbook. Note: I leave out the precondition assertion checking to simplify the presentation. --]] -- 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 local function deriv(f,dx) return function(x) -- return a function (closure) return (f(x+dx) - f(x)) / dx end end -- Partial testing local cube = function(x) return x * x * x end local DX = 0.001 local derivCube = deriv(cube,DX) -- returns one-argument function local function actualDerivCube(x) return 3 * x * x end print("\nderivCube(5) ==> " .. derivCube(5)) print( "derivative of cube at 5 ==> " .. actualDerivCube(5)) print("\nderiv(cube,0.001)(6) ==> " .. deriv(cube,0.001)(6)) print( "derivative of cube at 6 ==> " .. actualDerivCube(6))