Skip to content

Instantly share code, notes, and snippets.

@suzuken suzuken/plisp.php
Created Sep 20, 2016

Embed
What would you like to do?
<?php
function reduce($carry, $item) {
$carry -= $item;
return $carry;
}
function multi($carry, $item) {
$carry *= $item;
return $carry;
}
function div($carry, $item) {
$carry /= $item;
return $carry;
}
function myeval($tokens)
{
$env = [];
foreach ($tokens as $ex) {
$t = $ex[0];
switch (gettype($t)) {
case "string":
switch ($t) {
case "+":
return array_sum(array_slice($ex, 1));
case "-":
return array_reduce(array_slice($ex, 2), "reduce", $ex[1]);
case "*":
return array_reduce(array_slice($ex, 2), "multi", $ex[1]);
case "/":
return array_reduce(array_slice($ex, 2), "div", $ex[1]);
}
default:
break;
}
}
}
function parse($str)
{
$tokens = [];
if ($str[0] !== "(") {
return false;
}
// body
$body = strstr(substr($str, 1), ")", true);
$tokens []= explode(" ", $body);
return $tokens;
}
function main($argc, $argv)
{
if ( $argc !== 2 || $argv[1] === null) {
fwrite(STDERR, "argument required");
exit(1);
}
$tokens = parse($argv[1]);
return myeval($tokens);
}
echo main($argc, $argv);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.