File tree Expand file tree Collapse file tree 3 files changed +51
-1
lines changed
PascalInterpreter.playground
SwiftPascalInterpreter/SwiftPascalInterpreter Expand file tree Collapse file tree 3 files changed +51
-1
lines changed Original file line number Diff line number Diff line change @@ -21,3 +21,6 @@ print(parser.expr())
2121
2222let rpn = RPN ( " (5 + 3) * 12 / 3 " )
2323rpn. eval ( )
24+
25+ let ln = LISPNotation ( " (2 + 3 * 5) " )
26+ ln. eval ( )
Original file line number Diff line number Diff line change @@ -97,6 +97,24 @@ extension Interpreter: CustomStringConvertible {
9797 }
9898}
9999
100+ extension Parser : CustomStringConvertible {
101+ public var description : String {
102+ return " Parser "
103+ }
104+ }
105+
106+ extension RPN : CustomStringConvertible {
107+ public var description : String {
108+ return " Reverse polish notation "
109+ }
110+ }
111+
112+ extension LISPNotation : CustomStringConvertible {
113+ public var description : String {
114+ return " LISP notation "
115+ }
116+ }
117+
100118extension AST : CustomStringConvertible {
101119 public var description : String {
102120 return treeString ( self , using: { node in
Original file line number Diff line number Diff line change 88
99import Foundation
1010
11+ public protocol Notation {
12+ func eval( ) -> String
13+ }
14+
1115/**
1216 Reverse polish notation
1317 */
14- public class RPN {
18+ public class RPN : Notation {
1519 private let parser : Parser
1620
1721 public init ( _ text: String ) {
@@ -32,3 +36,28 @@ public class RPN {
3236 }
3337 }
3438}
39+
40+ /**
41+ LISP notation
42+ */
43+ public class LISPNotation : Notation {
44+ private let parser : Parser
45+
46+ public init ( _ text: String ) {
47+ parser = Parser ( text)
48+ }
49+
50+ public func eval( ) -> String {
51+ let node = parser. expr ( )
52+ return visit ( node)
53+ }
54+
55+ private func visit( _ node: AST ) -> String {
56+ switch node {
57+ case let . number( value) :
58+ return " \( value) "
59+ case let . binaryOperation( left: left, operation: operation, right: right) :
60+ return " ( \( operation. shortDescription) \( visit ( left) ) \( visit ( right) ) ) "
61+ }
62+ }
63+ }
You can’t perform that action at this time.
0 commit comments