PHP – Nested Tuple
Here’s a quick nested tuple [list of head and tail, where tail is the list minus the head]. I wrote this for a current project I’m working on. It works with any parameters except one array. If you only pass one array, it will convert your one array into a list of Tuples.
<?php
/**
* Tuple is a list of variables. Really it is a head and a tail, where the tail
* is also a Tuple. (Tuple(n)=head + Tuple(n-1))
*/
class Tuple
{
public $head;
public $tail;
public function __construct($args = null)
{
if(! (is_array($args) && func_num_args() == 1))
{
// get all the arguments and package them as an array
$args = func_get_args();
}
// take the first element and use that as the head of the list
$this->head = array_shift($args);
// if there are still args left, make a new list and use that as tail
if(count($args)>0)
{
// pass the remainder
$this->tail = new Tuple($args);
}
}
}
?>
/**
* Tuple is a list of variables. Really it is a head and a tail, where the tail
* is also a Tuple. (Tuple(n)=head + Tuple(n-1))
*/
class Tuple
{
public $head;
public $tail;
public function __construct($args = null)
{
if(! (is_array($args) && func_num_args() == 1))
{
// get all the arguments and package them as an array
$args = func_get_args();
}
// take the first element and use that as the head of the list
$this->head = array_shift($args);
// if there are still args left, make a new list and use that as tail
if(count($args)>0)
{
// pass the remainder
$this->tail = new Tuple($args);
}
}
}
?>
Here’s some usage and output:
That prints out:
Tuple Object
(
[head] => 1
[tail] => Tuple Object
(
[head] => 2
[tail] => Tuple Object
(
[head] => 3
[tail] => Tuple Object
(
[head] => 4
[tail] =>
)
)
)
)
(
[head] => 1
[tail] => Tuple Object
(
[head] => 2
[tail] => Tuple Object
(
[head] => 3
[tail] => Tuple Object
(
[head] => 4
[tail] =>
)
)
)
)
Tags: PHP