Étude 7-1: Simple Higher Order Functions

In calculus, the derivative of a function is “a measure of how a function changes as its input changes” (Wikipedia). For example, if an object is traveling at a constant velocity, that velocity is the same from moment to moment, so the derviative is zero. If an object is falling, its velocity changes a little bit as the object starts falling, and then falls faster and faster as time goes by.

You can calculate the rate of change of a function by calculating: (F(X + Delta) - F(X)) / Delta, where Delta is the interval between measurements. As Delta approaches zero, you get closer and closer to the true value of the derivative.

Write a module named calculus with a function derivative/2. The first argument is the function whose derivative you wish to find, and the second argument is the point at which you are measuring the derivative.

What should you use for a value of Delta? I used 1.0e-10, as that is a small number that approaches zero.

Here is some sample output.

1> c(calculus).
{ok,calculus}
2> F1 = fun(X) -> X * X end.
#Fun<erl_eval.6.82930912>
3> F1(3).
9
4> calculus:derivative(F1, 3).
6.000000496442226
5> calculus:derivative(fun(X) -> 3 * X * X + 2 * X + 1 end, 5).
32.00000264769187
6> calculus:derivative(fun math:sin/1, 0).
1.0
  • Line 3 is a test to see if the F1 function works.
  • Line 5 shows that you don’t have to assign a function to a variable; you can define the function in line.
  • Line 6 shows how to refer to a function in another module. ...

Get Études for Erlang now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.