Created
March 23, 2011 14:16
-
-
Save fmarani/883149 to your computer and use it in GitHub Desktop.
Monad in PHP?!
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 | |
/** | |
* Monad boxing integer side effects | |
* | |
* @package default | |
* @subpackage default | |
* @author Federico Marani | |
**/ | |
class IntegerBox | |
{ | |
/** | |
* undocumented function | |
* | |
* @return void | |
**/ | |
public function __construct($value) | |
{ | |
$this->value = $value; | |
$this->isNaN = false; | |
$this->infinite = false; | |
} | |
/** | |
* undocumented function | |
* | |
* @return void | |
**/ | |
public static function identity($unboxedInt) | |
{ | |
return new IntegerBox($unboxedInt); | |
} | |
/** | |
* undocumented function | |
* | |
* @return void | |
**/ | |
public static function bind($boxedInt, $function) | |
{ | |
$newBox = @$function($boxedInt); | |
if ($newBox->value == null) | |
$newBox->infinite = true; | |
return $newBox; | |
} | |
/** | |
* undocumented function | |
* | |
* @return void | |
**/ | |
public function __toString() | |
{ | |
if ($this->isNaN) | |
return "NaN"; | |
if ($this->infinite) | |
return "Infinite"; | |
return strval($this->value); | |
} | |
} // END class IntegerBox | |
$plusOne = function($x) { return IntegerBox::identity($x->value + 1); }; | |
$one = IntegerBox::identity(1); | |
$two = IntegerBox::bind($one, $plusOne); | |
print "$two\n"; | |
$divideByZero = function($x) { return IntegerBox::identity(bcdiv($x->value, 0)); }; | |
$newVal = IntegerBox::bind($one, $divideByZero); | |
print "$newVal\n"; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment