[ create a new paste ] login | about

Link: http://codepad.org/xd3iuP7Y    [ raw code | output | fork ]

jcope - PHP, pasted on Sep 12:
<?php
	//the different operators map to their respective function
	$opers = array
	(
		'+' => function($val1, $val2){ return $val1+$val2; }, 
		'-' => function($val1, $val2){ return $val1-$val2; }, 
		'*' => function($val1, $val2){ return $val1*$val2; }, 
		'/' => function($val1, $val2){ return $val1/$val2; },
	);

	function evalExpr($input)
	{
		//split the input on white space
		$expr = preg_split("/[ \t\n]+/", $input);
		//create the stack
		$stack = array();
		foreach ($expr as $term)
			evaluate($stack, $term);
		//if this worked out correctly
		//we should only have the result on the stack
		if (sizeof($stack) == 1)
			return array_pop($stack);
	}

	function evaluate(&$stack, $term)
	{
		global $opers;
		//if this is a number
		if (is_numeric($term))
			//push it on the stack
			array_push($stack, $term);
		//if this is an operator
		else if (array_key_exists($term, $opers))
		{
			//pop top two values off the stack
			$val2 = array_pop($stack);
			$val1 = array_pop($stack);
			//get the function that goes with this operator
			$func = $opers[$term];
			//get the result and push it back on the stack
			array_push($stack, $func($val1, $val2));
		}
	}
?>


Output:
1
2

Parse error: syntax error, unexpected T_FUNCTION on line 5


Create a new paste based on this one


Comments: