Friday, April 27, 2012

If all of your state is on the stack then you are doing functional programming

Consider this: This is imperative code, it uses variables with state, but from the outside it is a pure mathematical function. This is because all of its variables are created anew when the function is being executed and destroyed after that. It does not matter that the variables contain simple values: This can also be purely functional provided that Markdent::Simple::Document does not use globals or system calls.

Imagine that this was enforced by the compiler/interpreter - maybe with a new keyword function, or something. I have the feeling that this would be very similar to how use strict works - giving the end user some kind of safety.


Reini Urban said...

For functional programming you would also need to enforce functions/ops without sideeffects. Since most perl ops have sideffects (not only print, also setting $_, _,...) it would be pretty hard to call perl functions functional.
sum is functional here, but even a simple hash iterator with while each will violate this. perl hash iterators are non-functional.

zby said...

Yeah - I actually wanted to add a note about the problem with the fact that in Perl even reading a variable can change it's state (by setting the number slot from the character value), but your examples are even better. Not so simple in Perl5.

zby said...

But on the other hand - catching all of these global actions (like setting unlocalized $_ in a library) is exactly why it would be very useful in Perl.