Created
September 20, 2016 11:31
-
-
Save suzuken/551a81199d907958b03f38dda22fcdd5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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