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:

Child process exited with error

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

Child process exited with error

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:

Child process exited with error

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.

Child process exited with error

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

Child process exited with error

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

Child process exited with error

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

<-   ->