220
|
1 |
// Shunting Yard Algorithm
|
|
2 |
// including Associativity for Operators
|
|
3 |
// =====================================
|
219
|
4 |
|
396
|
5 |
object C3b {
|
288
|
6 |
|
|
7 |
|
220
|
8 |
// type of tokens
|
219
|
9 |
type Toks = List[String]
|
|
10 |
|
220
|
11 |
// helper function for splitting strings into tokens
|
|
12 |
def split(s: String) : Toks = s.split(" ").toList
|
|
13 |
|
|
14 |
// left- and right-associativity
|
|
15 |
abstract class Assoc
|
|
16 |
case object LA extends Assoc
|
|
17 |
case object RA extends Assoc
|
219
|
18 |
|
|
19 |
|
220
|
20 |
// power is right-associative,
|
|
21 |
// everything else is left-associative
|
219
|
22 |
def assoc(s: String) : Assoc = s match {
|
|
23 |
case "^" => RA
|
|
24 |
case _ => LA
|
|
25 |
}
|
|
26 |
|
|
27 |
|
220
|
28 |
// the precedences of the operators
|
219
|
29 |
val precs = Map("+" -> 1,
|
220
|
30 |
"-" -> 1,
|
|
31 |
"*" -> 2,
|
|
32 |
"/" -> 2,
|
|
33 |
"^" -> 4)
|
219
|
34 |
|
220
|
35 |
// the operations in the basic version of the algorithm
|
219
|
36 |
val ops = List("+", "-", "*", "/", "^")
|
|
37 |
|
288
|
38 |
// (3) Implement the extended version of the shunting yard algorithm.
|
220
|
39 |
// This version should properly account for the fact that the power
|
|
40 |
// operation is right-associative. Apart from the extension to include
|
|
41 |
// the power operation, you can make the same assumptions as in
|
|
42 |
// basic version.
|
219
|
43 |
|
346
|
44 |
def syard(toks: Toks, st: Toks = Nil, out: Toks = Nil) : Toks = ???
|
220
|
45 |
|
219
|
46 |
|
220
|
47 |
// test cases
|
|
48 |
// syard(split("3 + 4 * 8 / ( 5 - 1 ) ^ 2 ^ 3")) // 3 4 8 * 5 1 - 2 3 ^ ^ / +
|
219
|
49 |
|
|
50 |
|
346
|
51 |
// (4) Implement a compute function that produces an Int for an
|
220
|
52 |
// input list of tokens in postfix notation.
|
|
53 |
|
346
|
54 |
def compute(toks: Toks, st: List[Int] = Nil) : Int = ???
|
219
|
55 |
|
|
56 |
|
220
|
57 |
// test cases
|
|
58 |
// compute(syard(split("3 + 4 * ( 2 - 1 )"))) // 7
|
|
59 |
// compute(syard(split("10 + 12 * 33"))) // 406
|
|
60 |
// compute(syard(split("( 5 + 7 ) * 2"))) // 24
|
|
61 |
// compute(syard(split("5 + 7 / 2"))) // 8
|
|
62 |
// compute(syard(split("5 * 7 / 2"))) // 17
|
|
63 |
// compute(syard(split("9 + 24 / ( 7 - 3 )"))) // 15
|
|
64 |
// compute(syard(split("4 ^ 3 ^ 2"))) // 262144
|
|
65 |
// compute(syard(split("4 ^ ( 3 ^ 2 )"))) // 262144
|
|
66 |
// compute(syard(split("( 4 ^ 3 ) ^ 2"))) // 4096
|
|
67 |
// compute(syard(split("( 3 + 1 ) ^ 2 ^ 3"))) // 65536
|
219
|
68 |
|
288
|
69 |
}
|