Created
February 21, 2011 16:26
-
-
Save zandev/837294 to your computer and use it in GitHub Desktop.
Functional data structures experiments in php
This file contains hidden or 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 øList { | |
| function getHead(); | |
| function getTail(); | |
| } | |
| class øSimpleList implements øList { | |
| function __construct($head, øList $tail) | |
| { | |
| $this->requireType($head, $tail); | |
| $this->head = $head; | |
| $this->tail = $tail; | |
| } | |
| function getHead() | |
| { | |
| return $this->head; | |
| } | |
| function getTail() | |
| { | |
| return $this->tail; | |
| } | |
| private function requireType($x, øList $xs) | |
| { | |
| if(null == $xs->getHead()) | |
| return true; | |
| $class = get_class($xs->getHead()); | |
| if(! $x instanceOf $class ) | |
| throw new Exception('Type Error'); | |
| } | |
| } function øList($head, øList $tail) {return new øSimpleList($head, $tail);} | |
| class øNullList implements øList { | |
| function getHead() {return null;} | |
| function getTail() {return null;} | |
| } function øNullList() {return new øNullList();} | |
| class øInt { | |
| function __construct($value) | |
| { | |
| if(!is_int($value)) | |
| throw new Exception('Type Error'); | |
| $this->value = $value; | |
| } | |
| } function øInt ($value) { return new øInt($value);} | |
| function toList(array $a) | |
| { | |
| $list = øNullList(); | |
| foreach($a as $n) | |
| { | |
| $list = øList(øInt(2),$list); | |
| } | |
| return $list; | |
| } | |
| var_dump(toList(range(1,10))); | |
| exit; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment