Matt Follett

Week 1: The Lambda Function

***UPDATE:  I modified the final example with Naveed’s (@ironcamel) suggestion, it looks much nicer now.***

***UPDATE: Christopher Bottom caught some vestigial lines of code in the final example, which I have removed.***

The Lambda Function is the building block of all functional programming.  It is also referred to as an anonymous function or sometimes in Perl as an anonymous subroutine.  Perl treats subroutines as first class data types.  Because of this it is incredibly simple to create, store, and invoke anonymous subroutines.  To create an anonymous subroutine you simply use the ‘sub’ keyword without putting a name between the keyword and the body.  For example:

Is an example of an anonymous subroutine.  Obviously it isn’t very useful though.  To make this useful we need to store the reference of that anonymous subroutine in a variable:

Now that we have an anonymous subroutine referenced by the $hello variable we can access it by dereferencing and calling it like so:

Anonymous subroutines are just like normal subroutines.  Because of this you can pass parameters in to them.  Passed in parameters are provided in @_ just like in a normal subroutine.  If an anonymous subroutine exists within a larger subroutine then both will have their own @_ within their scope and you won’t have to worry about them intermingling.

Without dereferencing and calling it you are simply referring to the variable itself, which you can pass around.  In fact, because these subroutine references are first class they can be treated the same as any other value.  This means that you can store subroutine references in arrays and in hashes (as both the key or the value), and that you can pass it along in subroutines.

This concludes this week’s installment in Functional Perl.  Next week will cover the next building block, closures.