Created
November 29, 2016 15:44
-
-
Save twslade/f25fbcadc3a6a917e350addfb43e7073 to your computer and use it in GitHub Desktop.
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 Functor{ | |
public function __invoke($function); | |
} | |
abstract class AFunctor implements Functor{ | |
protected $_storage = null; | |
public function __construct($data = null){ | |
$this->set($data); | |
} | |
public function get(){ | |
return $this->_storage; | |
} | |
public function set($data){ | |
$this->_storage = $data; | |
} | |
} | |
class JustANumber extends AFunctor{ | |
public function __invoke($function){ | |
return new JustANumber($function($this->_storage)); | |
} | |
} | |
class JustAnArray extends AFunctor{ | |
public function __invoke($function){ | |
return new JustAnArray(array_map(function($value) use ($function){ | |
return $function($value); | |
}, $this->_storage)); | |
} | |
} | |
function fMap($function, $functor){ | |
if(!$functor instanceof Functor){ | |
throw new Exception('Not a functor'); | |
} | |
return $functor($function); | |
} | |
$square = function($num){return $num*$num;}; | |
var_dump(fmap($square, new JustANumber(2))); | |
var_dump(fmap($square, new JustAnArray(array(1,2,3,4)))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment