Recent Tweets

Post Categoris

Example of Functional Programming in Three Web Languages

Functional programming is all the rage in the Javascript community this year, and I’ve been doing a lot of it lately because I’ve been using Redux on my latest project at work. It occurred to me that web developers have had some of the building blocks of functional programming for over two decades. Here are examples of a functional approach, mapping an array to a new array, in just three languages popular in web development, ones that I’m familiar with.

Perl has been used for web development basically since the beginning of the web, around 1994. PHP started as a web development tool in the late 1990s. JavaScript was built for client-side scripting around the same time, but really came into its own when Ajax became popular around 2005.

I mean for this to be a short post; so, I’m just going to show you the examples of array mapping I came up with in each language and their output.

Each example will take an array of computer-usable identifiers, with spaces represented by underscores like two_words. The example will create a new array of human-readable strings, suitable for output, like two words.

If you are interested in digging deeper, just search for the function names in each language and go from there. (I had to search to refresh my memory of the Perl and PHP syntax, so I know there is a wealth of information on this topic.)

Perl

Perl has a built-in function, map, which takes as arguments a code block and an array (or “list” as Perl likes to say). For each item in the array, the code block is called, with the value of Perl’s default variable, $_, set to that item. The code block can do whatever it wants to with the item, and return something that becomes a corresponding item in the new array.

PHP

PHP has a built-in function, array_map, which takes as arguments a reference to a function and an array. For each item in the array, the function is called, with the argument of that function set to that current item. The function can do whatever it wants to with the argument, and return something that becomes a corresponding item in the new array.

JavaScript

JavaScript arrays are a special type of JavaScript object that includes a map method. You call that method on an array, and it takes a function as an argument. For each item in the array, the function is called, with the argument of that function set to that current item. The function can do whatever it wants to with the argument, and return something that becomes a corresponding item in the new array.

Conclusion

Aside from trivial differences in syntax, the examples in each language are remarkably similar. While you could make an argument that the internals of one or another of these languages are better suited to functional programming, they all allow you to program in a functional style.