Name: Anonymous 2011-04-05 17:49
x >>= f >>= g >>= his
h(do_monad_magic(g(do_monad_magic(f(do_monad_magic(x))))))
x >>= f >>= g >>= hh(do_monad_magic(g(do_monad_magic(f(do_monad_magic(x))))))
function call($x, $f) { return $f($x); }
function identity($x) { return $x; }
class Monad {
protected $bind_;
protected $unit_;
public function __construct($bind = 'call', $unit = 'identity') {
$this->bind_ = $bind;
$this->unit_ = $unit;
}
public function unit($x) { return call_user_func($this->unit_, $x); }
public function bind($x, $f) { return call_user_func_array($this->bind_, array($x, $f)); }
}
$IdentityMonad = new Monad();
function lm_unit($x) { return array(0 => $x); }
function lm_append($x, $f) {
return array_merge(array_map($f, $x));
}
$ListMonad = new Monad('lm_append', 'lm_unit');
function add1($x) { return $x+1; }
print_r($ListMonad->bind($ListMonad->unit(2), 'add1'));
function Monad(bind, unit) {
this.bind = bind;
this.unit = unit;
}
Identity =
new Monad(function(x, f) { return f(x); },
function(x) { return x; });
List =
new Monad(function(x, f) {
var y = x.map(f);
return Array.prototype.concat.apply(y);
}, function (x) { return [x]; });
(define (make-monad bind unit)
(lambda (z . a)
(case z
((>>=) (apply bind a))
((unit) (apply unit a)))))
(define identity-m
(make-monad (λ (x f) (f x))
(λ (x) x)))
(define list-m
(make-monad (λ (x f) (apply append (map f x))) list))
(define maybe-m
(make-monad (λ (x f) (if x (f x) x)) (λ (x) x)))
(list-m '>>=
(list-m 'unit 2)
(lambda (x) (+ x 1)))