Implementing stack

 

We have seen the implementation of stacks in Chapter 4, Constructing Stacks and Queues. For simplicity, we won't discuss the whole stack operation again. We will jump right into the implementation of push, pop, and top operations using functional programming. Tarsana has lots of built-in functions for list operations. We will use their built-in functions to implement our functional operations of the stack. Here is the implementation:

 

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

use TarsanaFunctional as F;

$stack = [];

$push = Fappend(F\__(), F\__());
$top = Flast(F\__());
$pop = Finit(F\__());

$stack = $push(1, $stack);
$stack = $push(2, $stack);
$stack = $push(3, $stack);

echo "Stack is ".F oString($stack)." ";

$item = $top($stack);
$stack = $pop($stack);

echo "Pop-ed item: ".$item." ";
echo "Stack is ".F oString($stack)." ";

$stack = $push(4, $stack);

echo "Stack is ".F oString($stack)." ";

Here, we use the append function of Tarsana for the push operation, the last function we used here for the top operation, and the init function for the pop operation. The output of the following code is as follows:

Stack is [1, 2, 3]
Pop-ed item: 3
Stack is [1, 2]
Stack is [1, 2, 4]
..................Content has been hidden....................

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