functional perl code for fun

26 January 2011, 22:57

I have no formal functional programming training but being curious I’ve always paid attention to it.

Lately I was designing an API for a Perl module I’m about to release. I wanted to share how elegant the functional approach is compared to an iterative one.

The context: I’m building a module that implements a very weak cipher where each character of a string is rotated according to a formula that I wanted the user to control.

A naive approach would look like:

positional_rot_linear( $string, $m, $b );

with m and b of the y = mx + b fame. What about quadratic? For completeness I would need a:

positional_rot_quadratic( $string, $a, $b, $c );

with f(x) = ax^2+bx+c. But now, what about the fibonacci sequence or your own favorite sequence? Well, I would need a custom sequence that would provide an array of rotation indexes:

# fibonacci numbers
@rotations = ( 0, 1, 1, 2, 3, 5, 8, 13 ); 
positional_rot( $string, @rotations );

Here’s where the fun start. Why not delegate the control of the sequence entirely to the API user? We can do this if we accept as a parameter a function with a particular contract. For example, one where we provide the position and that would return the rotate value.

$linear_3x = sub {
    my $pos = shift;
    return (3 * $pos);
};
positional_rot( $string, $linear_3x );

Or, more compactly with an anonymous function and without the temporary value:

positional_rot( $string, sub { return (3 * shift); } );

The user then providing code is able to do pretty much what he wants!

# quadratic 5x^2 + 2x + 12
sub { 
    my $pos = shift;
    return (5 * $pos**2 + 2 * $pos + 12);
}
# rot13
sub { return 13; }

This actually reminds me of Java. I would have needed to set my method to expect an object of a certain interface and then create an implementation of that interface that suited my need. With Perl no need for all of that but you lose the static typing goodness, which tend to make errors happen at run time instead of compile time.

But that’s a whole other topic..

— Olivier Bilodeau

---

Comment

Textile Help

<-   ->