Created
June 9, 2012 16:31
-
-
Save homm/2901682 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 forth_calc($input) { | |
$stack = array(); | |
foreach (explode(' ', $input) as $chunk) { | |
if ($chunk === '+') { | |
$stack[] = array_pop($stack) + array_pop($stack); | |
} elseif ($chunk === '-') { | |
$stack[] = array_pop($stack) - array_pop($stack); | |
} elseif ($chunk === '*') { | |
$stack[] = array_pop($stack) * array_pop($stack); | |
} elseif ($chunk === '=') { | |
$stack[] = array_pop($stack) === array_pop($stack); | |
} elseif ($chunk === 'DUMP') { | |
var_dump($stack); | |
} elseif ($chunk === 'DUP') { | |
$stack[] = end($stack); | |
} else { | |
$stack[] = $chunk; | |
} | |
} | |
return $stack; | |
} | |
$input = '10 20 100 + - 20 * DUP 10 20 + *'; | |
$t = microtime(1); | |
for ($i = 0; $i < 100000; $i++) { | |
forth_calc($input); | |
} | |
echo 'Array: ', microtime(1) - $t, "\n"; | |
print_r(forth_calc($input)); |
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 forth_calc($input) { | |
$stack = array(); | |
$esi = 0; | |
foreach (explode(' ', $input) as $chunk) { | |
if ($chunk === '+') { | |
$stack[--$esi - 1] = $stack[$esi] + $stack[$esi - 1]; | |
} elseif ($chunk === '-') { | |
$stack[--$esi - 1] = $stack[$esi] - $stack[$esi - 1]; | |
} elseif ($chunk === '*') { | |
$stack[--$esi - 1] = $stack[$esi] * $stack[$esi - 1]; | |
} elseif ($chunk === '=') { | |
$stack[--$esi - 1] = $stack[$esi] === $stack[$esi - 1]; | |
} elseif ($chunk === 'DUMP') { | |
var_dump($stack); | |
} elseif ($chunk === 'DUP') { | |
$stack[$esi] = $stack[$esi - 1]; | |
$esi++; | |
} else { | |
$stack[$esi++] = $chunk; | |
} | |
} | |
return $stack; | |
} | |
$input = '10 20 100 + - 20 * DUP 10 20 + *'; | |
$t = microtime(1); | |
for ($i = 0; $i < 100000; $i++) { | |
forth_calc($input); | |
} | |
echo 'Array: ', microtime(1) - $t, "\n"; | |
print_r(forth_calc($input)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment