Skip to content

Instantly share code, notes, and snippets.

@twslade
Created November 29, 2016 15:44
Show Gist options
  • Save twslade/f25fbcadc3a6a917e350addfb43e7073 to your computer and use it in GitHub Desktop.
Save twslade/f25fbcadc3a6a917e350addfb43e7073 to your computer and use it in GitHub Desktop.
<?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