Skip to content

Instantly share code, notes, and snippets.

@copperwall
Created December 29, 2016 03:08
Show Gist options
  • Save copperwall/d63c54ddcc3774a7b5501e7f684d8012 to your computer and use it in GitHub Desktop.
Save copperwall/d63c54ddcc3774a7b5501e7f684d8012 to your computer and use it in GitHub Desktop.
Don't ask why
<?php
/**
* cons for PHP
*/
// constructs a pair
function cons($a, $b) {
return function($m) use ($a, $b) {
if ($m == 0) {
return $a;
} else if ($m == 1) {
return $b;
} else {
throw new Exception("m is not 0 or 1 CONS");
}
};
}
// returns the first item in a pair
function car($x) {
return $x(0);
}
// returns the second item in a pair
function cdr($x) {
return $x(1);
}
// same as car, mostly used on lists
function first($x) {
return car($x);
}
// same as cdr, mostly used on lists
function rest($x) {
return cdr($x);
}
// constructs a list built from nested pairs
// (list 1 2 3 4)
function plist(...$items) {
if (empty($items))
return null;
return cons(array_shift($items), plist(...$items));
}
/**
* Example Code
*/
$pair1 = cons(1, 2);
$pair2 = cons(3, 4);
// "1"
car($pair1);
// "2"
cdr($pair1);
// nested pair
$pair = cons($pair1, $pair2);
// "1"
$one = car(car($pair));
// "3"
$two = car(cdr($pair));
// Recursive sum example
function sum($list) {
if (is_null($list))
return 0;
return first($list) + sum(rest($list));
}
// "10"
sum(plist(1, 2, 3, 4));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment