Skip to content

Commit 6f6aa4a

Browse files
committed
✨ adding a way to print the expression in LISP style
1 parent b639ace commit 6f6aa4a

File tree

3 files changed

+51
-1
lines changed

3 files changed

+51
-1
lines changed

PascalInterpreter.playground/Contents.swift

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,6 @@ print(parser.expr())
2121

2222
let rpn = RPN("(5 + 3) * 12 / 3")
2323
rpn.eval()
24+
25+
let ln = LISPNotation("(2 + 3 * 5)")
26+
ln.eval()

SwiftPascalInterpreter/SwiftPascalInterpreter/Extensions.swift

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff 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+
100118
extension AST: CustomStringConvertible {
101119
public var description: String {
102120
return treeString(self, using: { node in

SwiftPascalInterpreter/SwiftPascalInterpreter/Notations.swift

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,14 @@
88

99
import 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+
}

0 commit comments

Comments
 (0)