Getting started with Tarsana

Tarsana is an open source library written by Amine Ben Hammou and is available on GitHub for download. It is inspired from Ramda JS, a functional programming library for JavaScript. It does not have any dependencies and has more than 100 predefined functions to use for different purposes. Functions in FP are spread over different modules and there are several modules such as functions, list, object, string, math, operators, and common. Tarsana can be downloaded from GitHub (https://github.com/Tarsana/functional) or can be installed via composer.

composer require Tarsana/functional

Once the library is downloaded, we have to use it by importing the TarsanaFunctional namespace, just like the following code:

use TarsanaFunctional as F; 

One of the interesting features of Tarsana is that we can convert any of our existing functions to a curried function. For example, if we want to use our sum function using Tarsana, then it will look like this:

require __DIR__ . '/vendor/autoload.php'; 

use TarsanaFunctional as F;

$add = Fcurry(function($x, $y, $z) {
return $x + $y + $z;
});

echo $add(1, 2, 4)." ";
$addFive = $add(5);
$addSix = $addFive(6);
echo $addSix(2);

This will produce the output of 7 and 13, respectively. Tarsana also has an option to keep place holders using the __() function. The following example shows the array reduce and array sum of the entries provided in the placeholder:

$reduce = Fcurry('array_reduce'); 
$sum = $reduce(F\__(), Fplus());
echo $sum([1, 2, 3, 4, 5], 0);

Tarsana also provides a piping functionality, where we can apply a series of functions from left to right. The leftmost function may have any arity; the remaining functions must be unary. The result of piping is not curried. Let's consider the following example:

$square = function($x) { return $x * $x; }; 
$addThenSquare = Fpipe(Fplus(), $square);
echo $addThenSquare(2, 3);

As we have already explored some features of Tarsana, we are ready to start our functional data structures using Tarsana. We will also implement those data structures using simple PHP functions so that we have both parts covered, if we do not want to use functional programming. Let's get started with the implementation of stack.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset