Example of Functional Programming in Three Web Languages

Van Jesse Wilson
Sep 9, 2017 · 4 min read
  1. PHP
  2. JavaScript

Perl

Perl Logo
Perl Logo
my @columns = ('card_type', 'full_name', 'transaction_date', 'transaction_amount', 'transaction_status');

print "@columns\n";

my @human_names = map { $_ =~ s/_/ /gr } @columns;

print "@human_names\n";
perl foo.pl
card_type full_name transaction_date transaction_amount transaction_status
card type full name transaction date transaction amount transaction status

PHP

PHP Logo
PHP Logo
<?php

function make_human_readable($item) {
return preg_replace('/_/', ' ', $item);
}

$columns = ['card_type', 'full_name', 'transaction_date', 'transaction_amount', 'transaction_status'];

print_r($columns);

$human_names = array_map("make_human_readable", $columns);

print_r($human_names);

?>
php bar.php
Array
(
[0] => card_type
[1] => full_name
[2] => transaction_date
[3] => transaction_amount
[4] => transaction_status
)
Array
(
[0] => card type
[1] => full name
[2] => transaction date
[3] => transaction amount
[4] => transaction status
)

JavaScript

JavaScript Logo
JavaScript Logo
function makeHumanReadable(item) {
return item.replace(/_/, ' ');
}

const columns = ['card_type', 'full_name', 'transaction_date', 'transaction_amount', 'transaction_status'];

console.log(columns);

const humanNames = columns.map(makeHumanReadable);

console.log(humanNames);
node baz.js
[ 'card_type',
'full_name',
'transaction_date',
'transaction_amount',
'transaction_status' ]
[ 'card type',
'full name',
'transaction date',
'transaction amount',
'transaction status' ]

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.


    Van Jesse Wilson

    Written by

    Web developer, husband, father, and hiker. The world is too dangerous for anything but truth and too small for anything but love.

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade