Since functions are first class objects in Perl, we can store a function reference in a variable, we can pass a function as an argument into another function and we can write a function whose return type is also a function. This allows us to implement the derivative function from Calculus as a closure.

derivative.pl

#!/usr/local/bin/perl -w use strict; ## ## package: Main ## purpose: Demonstrate derivative function ## author: Joel Dalley ## version 2008/Apr/12 ## package Main; { # Delta x use constant dx => 1e-10; # Estimate Pi use constant pi => 3.14159265; # Take a function reference $f and return a # reference to the derivative function of $f sub derivative { my $f = shift; return sub { my $x = shift; return ($f->($x + dx) - $f->($x)) / dx; } } # A few examples D_CUBE_X: { # cube x = x^3 sub cube { $_[0] ** 3 } # cube' x = 3 x^2 my $df = derivative(\&cube); # print cube' 1, cube' 10, cube' 100 print join "\n", $df->(1), $df->(10), $df->(100), "\n"; } D_SIN_X: { # sin' x = cos x my $df = derivative(sub{ sin($_[0]) }); # print sin' 0, sin' pi/2, sin' pi and sin' 3pi/2 print join "\n", $df->(0), $df->(pi/2), $df->(pi), $df->(3*pi/2), "\n"; } D_LOG_X: { # ln' x = 1 / x my $df = derivative(sub{ log($_[0]) }); # print ln' 1 print $df->(1), "\n"; } } 1; __END__

The above code outputs the following:

3.00000024822111 300.000237984932 30000.2284348011 1 0 -1.00000008274037 0 1.00000008269037