Skip to content

Instantly share code, notes, and snippets.

@morrisonlevi
Created March 25, 2015 16:07
Show Gist options
  • Save morrisonlevi/e492bdcc86a80f41c37d to your computer and use it in GitHub Desktop.
Save morrisonlevi/e492bdcc86a80f41c37d to your computer and use it in GitHub Desktop.
Implementing a very basic set using inheritance / polymorphism
<?php
class EmptyNode implements Node {
function add($value) {
return new ValueNode($this, $this, $value);
}
function contains($value) {
return false;
}
}
<?php
interface Node {
function add($value);
function contains($value);
}
<?php
class Set {
/**
* @var Node
*/
private $root;
function __construct() {
$this->root = new EmptyNode();
}
function add($value) {
$this->root = $this->root->add($value);
}
function contains($value) {
return $this->root->contains($value);
}
}
<?php
class ValueNode implements Node {
public $left;
public $right;
public $value;
function __construct(Node $left, Node $right, $value) {
$this->value = $value;
$this->left = $left;
$this->right = $right;
}
function add($value) {
if ($value < $this->value) {
return $this->left->add($value);
} else if ($value > $this->value) {
return $this->right->add($value);
} else {
return $this;
}
}
function contains($value) {
if ($value < $this->value) {
return $this->left->contains($value);
} else if ($value > $this->value) {
return $this->right->contains($value);
} else {
return true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment