Implementing a queue

We can implement a queue using Tarsana and the built-in functions for list operations. We will use the array for queue representation as well using this code:

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

use TarsanaFunctional as F;

$queue = [];

$enqueue = Fappend(F\__(), F\__());
$head = Fhead(F\__());
$dequeue = F ail(F\__());

$queue = $enqueue(1, $queue);
$queue = $enqueue(2, $queue);
$queue = $enqueue(3, $queue);

echo "Queue is ".F oString($queue)." ";

$item = $head($queue);
$queue = $dequeue($queue);

echo "Dequeue-ed item: ".$item." ";
echo "Queue is ".F oString($queue)." ";

$queue = $enqueue(4, $queue);

echo "Queue is ".F oString($queue)." ";

Here, we use the append function to perform enqueue, and the head and tail functions for the first item in the queue and dequeuer, respectively. Here is the output of the preceding code:

Queue is [1, 2, 3]
Dequeue-ed item: 1
Queue is [2, 3]
Queue is [2, 3, 4]

Now, we will shift our focus to implementing hierarchical data using simple PHP functions instead of classes and objects. Since functional programming is still a new topic in PHP, implementation of hierarchical data might seem challenging and also time consuming. Instead, we will convert our hierarchical data implementation using basic PHP functions along with some basic functional programming concept such as first-class functions and higher order functions. So, let's implement a binary tree.

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

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