This commit is contained in:
Ingy döt Net 2013-10-27 22:24:23 +00:00
parent 6f050a029e
commit 776bba907c
3887 changed files with 59894 additions and 7280 deletions

View file

@ -0,0 +1,27 @@
(* binop : ('a -> 'a -> 'a) -> 'a list -> 'a list *)
let binop op = function
| b::a::r -> (op a b)::r
| _ -> failwith "invalid expression"
(* interp : float list -> string -> string * float list *)
let interp s = function
| "+" -> "add", binop ( +. ) s
| "-" -> "subtr", binop ( -. ) s
| "*" -> "mult", binop ( *. ) s
| "/" -> "divide", binop ( /. ) s
| "^" -> "exp", binop ( ** ) s
| str -> "push", (float_of_string str) :: s
(* interp_and_show : float list -> string -> float list *)
let interp_and_show s inp =
let op,s' = interp s inp in
Printf.printf "%s\t%s\t" inp op;
List.(iter (Printf.printf "%F ") (rev s'));
print_newline ();
s'
(* rpn_eval : string -> float list *)
let rpn_eval str =
Printf.printf "Token\tAction\tStack\n";
let ss = Str.(split (regexp_string " ") str) in
List.fold_left interp_and_show [] ss

View file

@ -1,24 +1,45 @@
<?php
// RPN Calculator
//
// Nigel Galloway - April 3rd., 2012
//
$WSb = '(?:^|\s+)';
$WSa = '(?:\s+|$)';
$num = '([+-]?(?:\.\d+|\d+(?:\.\d*)?))';
$op = '([-+*\/^])';
function rpn($postFix){
$stack = Array();
echo "Input\tOperation\tStack\tafter\n" ;
$token = explode(" ", trim($postFix));
$count = count($token);
for($i = 0 ; $i<$count;$i++)
{
echo $token[$i] ." \t";
$tokenNum = "";
if (is_numeric($token[$i])) {
echo "Push";
array_push($stack,$token[$i]);
}
else
{
echo "Operate";
$secondOperand = end($stack);
array_pop($stack);
$firstOperand = end($stack);
array_pop($stack);
function myE($m) {
return $m[3] == '^' ? ' ' . pow($m[1], $m[2]) . ' ' : ' ' . eval("return " . $m[1] . $m[3] . $m[2] . ";") . ' ';
if ($token[$i] == "*")
array_push($stack,$firstOperand * $secondOperand);
else if ($token[$i] == "/")
array_push($stack,$firstOperand / $secondOperand);
else if ($token[$i] == "-")
array_push($stack,$firstOperand - $secondOperand);
else if ($token[$i] == "+")
array_push($stack,$firstOperand + $secondOperand);
else if ($token[$i] == "^")
array_push($stack,pow($firstOperand,$secondOperand));
else {
die("Error");
}
}
echo "\t\t" . implode(" ", $stack) . "\n";
}
return end($stack);
}
while (!feof(STDIN)) {
$s = trim(fgets(STDIN));
if ($s == '')
continue;
do {
$s = preg_replace_callback("/$WSb$num\\s+$num\\s+$op$WSa/", "myE", $s, -1, $n);
} while ($n);
echo floatval($s) . "\n";
}
echo "Compute Value: " . rpn("3 4 2 * 1 5 - 2 3 ^ ^ / + ");
?>