PHP Reverse Polish notation 逆波蘭式


朋友問了一個關於逆波蘭式的問題.
程式不好.用了 Interpreter 設計模式參上了
記錄一下.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php
interface Expression {
public function interpret(array $s);
}

class ExperssionNumber implements Expression {
private $number;

public function __construct($number) {
$this->number = $number;
}

public function interpret(array $s) {
array_push($s, $this->number);
}
}

class ExperssionPlus implements Expression {
public function interpret(array $s) {
array_push($s, array_pop($s) + array_pop($s));
}
}

class ExpressionMinus implements Expression {
public function interpret(array $s) {
array_push($s, - array_pop($s) + array_pop($s));
}
}

class Parser {
private $parse_tree = array();

public function __construct($s) {
foreach(explode(" ", $s) as $token) {
switch($token) {
case "+": array_push($this->parse_tree, new ExperssionPlus()); break;
case "-": array_push($this->parse_tree, new ExpressionMinus()); break;
default: array_push($this->parse_tree, new ExperssionNumber($token)); break;
}
}
}

public function evaluate() {
$context = array();
foreach($this->parse_tree as $expression) {
$expression->interpret(&$context);
}
return array_pop($context);
}
}

class Test {
public static function run($experssion) {
($parser = new Parser($experssion)) && print($parser->evaluate()."\n");
}
}

Test::run("100 32 25 - +"); // “100 32 25 - +” > 32-25+100
?>