Skip to content

Instantly share code, notes, and snippets.

@LightAndLight
Created January 9, 2017 23:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LightAndLight/dfa23f4d929dfc5384fe05190872f32c to your computer and use it in GitHub Desktop.
Save LightAndLight/dfa23f4d929dfc5384fe05190872f32c to your computer and use it in GitHub Desktop.
Functional PHP
<?php
/*
Original Code
data List a = Nil | Cons a (List a)
ifte : Bool -> a -> a -> a
ifte cond a b = case cond of { true -> a; false -> b }
filter : (a -> Bool) -> List a -> List a
filter = rec filter' pred list = case list of {
Nil -> Nil;
Cons a rest -> ifte (pred a) (Cons a (filter' pred rest)) (filter' pred rest)
} in filter'
test : List Bool
test = filter (\x. x) (Cons true (Cons false (Cons true Nil)))
*/
class NilCon {
public function __construct() {
$this->values = array();
}
}
$Nil = new NilCon();
class ConsCon {
public function __construct($a1, $a2) {
$this->values = array($a1, $a2);
}
}
$Cons = function($a1) {
return function($a2) use ($a1) {
return new ConsCon($a1, $a2);
};
};
$ifte = function($cond) {
return function($a) use ($cond) {
return function($b) use ($a, $cond) {
return (function() use ($a, $b, $cond) {
if ($cond === true) {
return $a;
}
if ($cond === false) {
return $b;
}
})();
};
};
};
$filter = (function() use ($Cons, $Nil, $ifte) {
$filterPrime = function($pred) use ($Cons, $Nil, &$filterPrime, $ifte) {
return function($list) use ($Cons, $Nil, &$filterPrime, $ifte, $pred) {
return (function() use ($Cons, $Nil, &$filterPrime, $ifte, $list, $pred) {
if ($list instanceof NilCon) {
return $Nil;
}
if ($list instanceof ConsCon) {
$a = $list->values[0];
$rest = $list->values[1];
return $ifte($pred($a))($Cons($a)($filterPrime($pred)($rest)))($filterPrime($pred)($rest));
}
})();
};
};
return $filterPrime;
})();
$test = $filter(function($x) use ($filter) {
return $x;
})($Cons(true)($Cons(false)($Cons(true)($Nil))));
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment