Created
March 25, 2015 16:07
-
-
Save morrisonlevi/e492bdcc86a80f41c37d to your computer and use it in GitHub Desktop.
Implementing a very basic set using inheritance / polymorphism
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class EmptyNode implements Node { | |
function add($value) { | |
return new ValueNode($this, $this, $value); | |
} | |
function contains($value) { | |
return false; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
interface Node { | |
function add($value); | |
function contains($value); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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