disclaimer: this is just my inaccurate grasp of the subject - please feel free to comment
As I understand it functional programming is a method of writing programs. It implies structuring programs based on functions that are supposed to have no side-effects:
sub append_stuff {
my ($input) = @_;
$input . "stuff";
}
In this case the function &append_stuff has no side-effects. it returns a new string composed of the $input argument appended with the string "stuff". Contrast with:
sub modify_stuff {
$_[0] .= "stuff";
}
Which will return the $input argument appended with the string "stuff", but will also modify the $input string itself:
my $input = "some";
print append_stuff($input),"\n";
print "$input\n";
print modify_stuff($input),"\n";
print "$input\n";
__END__
somestuff
some
somestuff
somestuff
The advantage of using the functional variant is that it's much easier to follow what the program is doing than in the second case. It is supposed to decrease action at a distance.
All this leads to things like passing functions as arguments to functions and creating new functions at runtime (and closures). Perl supports all three, so perl might be considered a functional programming language.
On the other hand, functional programming languages generally try to avoid side-effects in build-in functions or at least offer a choice between a modifying and a non-modifying variant. Perl doesn't really do that. In the case of regex-replace:
my $input = "some";
print s/ome/tuff/;
print $input;
__END__
1stuff
So, the s/// operator is clearly not an example of a "clean" functional operator since it modifies its argument.
I should probably be clear that it is very unpractical to force the "no side-effects" rule in the more broad sense - IO is one area where you're more or less forced to have side-effects - though most side effects occur "outside" the program itself - and most functional programming languages support some kind of modifying function calls (you could probably abuse closures if they don't offer any other way).
Just my 2 cents. Another language you might want to take a look at is Lisp. Go read. There's more out there than Java :-)
updated: reworded explanation of &modify_stuff
|