Skip to content

Commit f11402f

Browse files
authored
Merge pull request #25 from bvwells/interpreter
Implement interpreter design pattern #11
2 parents edd9e63 + 0c355e7 commit f11402f

File tree

3 files changed

+164
-30
lines changed

3 files changed

+164
-30
lines changed

README.md

Lines changed: 30 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -36,42 +36,42 @@ Behavioral | [`github.com/bvwells/go-patterns/behavioral`][behavioral-ref] | Beh
3636

3737
## Creational [![GoDoc](https://godoc.org/github.com/bvwells/go-patterns/creational?status.svg)](https://godoc.org/github.com/bvwells/go-patterns/creational)
3838

39-
Name | Description | Status
40-
-----------|-------------------------------------------|------------
41-
[`Abstract Factory`](./creational/abstract_factory.go) | Provide an interface for creating families of related or dependent objects without specifying their concrete classes. | Implemented
42-
[`Builder`](./creational/builder.go) | Separate the construction of a complex object from its representation, allowing the same construction process to create various representations. | Implemented
43-
[`Factory Method`](./creational/factory_method.go) | Define an interface for creating a single object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses. | Implemented
44-
[`Object Pool`](./creational/object_pool.go) | Avoid expensive acquisition and release of resources by recycling objects that are no longer in use. Can be considered a generalisation of connection pool and thread pool patterns. | Implemented
45-
[`Prototype`](./creational/prototype.go) | Specify the kinds of objects to create using a prototypical instance, and create new objects from the 'skeleton' of an existing object, thus boosting performance and keeping memory footprints to a minimum. | Implemented
46-
[`Singleton`](./creational/singleton.go) | Ensure a class has only one instance, and provide a global point of access to it. | Implemented
39+
Name | Description
40+
-----------|-------------------------------------------
41+
[`Abstract Factory`](./creational/abstract_factory.go) | Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
42+
[`Builder`](./creational/builder.go) | Separate the construction of a complex object from its representation, allowing the same construction process to create various representations.
43+
[`Factory Method`](./creational/factory_method.go) | Define an interface for creating a single object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
44+
[`Object Pool`](./creational/object_pool.go) | Avoid expensive acquisition and release of resources by recycling objects that are no longer in use. Can be considered a generalisation of connection pool and thread pool patterns.
45+
[`Prototype`](./creational/prototype.go) | Specify the kinds of objects to create using a prototypical instance, and create new objects from the 'skeleton' of an existing object, thus boosting performance and keeping memory footprints to a minimum.
46+
[`Singleton`](./creational/singleton.go) | Ensure a class has only one instance, and provide a global point of access to it.
4747

4848
## Structural [![GoDoc](https://godoc.org/github.com/bvwells/go-patterns/structural?status.svg)](https://godoc.org/github.com/bvwells/go-patterns/structutal)
4949

50-
Name | Description | Status
51-
-----------|-------------------------------------------|------------
52-
[`Adapter`](./structural/adapter.go) | Convert the interface of a class into another interface clients expect. An adapter lets classes work together that could not otherwise because of incompatible interfaces. The enterprise integration pattern equivalent is the translator. | Implemented
53-
[`Bridge`](./structural/bridge.go) | Decouple an abstraction from its implementation allowing the two to vary independently. | Implemented
54-
[`Composite`](./structural/composite.go) | Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly. | Implemented
55-
[`Decorator`](./structural/decorator.go) | Attach additional responsibilities to an object dynamically keeping the same interface. Decorators provide a flexible alternative to subclassing for extending functionality. | Implemented
56-
[`Facade`](./structural/facade.go) | Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use. | Implemented
57-
[`Flyweight`](./structural/flyweight.go) | Use sharing to support large numbers of similar objects efficiently. | Implemented
58-
[`Proxy`](./structural/proxy.go) | Provide a surrogate or placeholder for another object to control access to it. | Implemented
50+
Name | Description
51+
-----------|-------------------------------------------
52+
[`Adapter`](./structural/adapter.go) | Convert the interface of a class into another interface clients expect. An adapter lets classes work together that could not otherwise because of incompatible interfaces. The enterprise integration pattern equivalent is the translator.
53+
[`Bridge`](./structural/bridge.go) | Decouple an abstraction from its implementation allowing the two to vary independently.
54+
[`Composite`](./structural/composite.go) | Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
55+
[`Decorator`](./structural/decorator.go) | Attach additional responsibilities to an object dynamically keeping the same interface. Decorators provide a flexible alternative to subclassing for extending functionality.
56+
[`Facade`](./structural/facade.go) | Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.
57+
[`Flyweight`](./structural/flyweight.go) | Use sharing to support large numbers of similar objects efficiently.
58+
[`Proxy`](./structural/proxy.go) | Provide a surrogate or placeholder for another object to control access to it.
5959

6060
## Behavioral [![GoDoc](https://godoc.org/github.com/bvwells/go-patterns/behavioral?status.svg)](https://godoc.org/github.com/bvwells/go-patterns/behavioral)
6161

62-
Name | Description | Status
63-
-----------|-------------------------------------------|------------
64-
[`Chain of Responsibility`](./behavioral/chain_of_responsibility.go) | Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it. | Implemented
65-
[`Command`](./behavioral/command.go) | Encapsulate a request as an object, thereby allowing for the parameterization of clients with different requests, and the queuing or logging of requests. It also allows for the support of undoable operations. | Implemented
66-
[`Interpreter`](./behavioral/interpreter.go) | Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language. |
67-
[`Iterator`](./behavioral/iterator.go) | Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation. | Implemented
68-
[`Mediator`](./behavioral/mediator.go) | Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it allows their interaction to vary independently. | Implemented
69-
[`Memento`](./behavioral/memento.go) | Without violating encapsulation, capture and externalize an object's internal state allowing the object to be restored to this state later. | Implemented
70-
[`Observer`](./behavioral/observer.go) | Define a one-to-many dependency between objects where a state change in one object results in all its dependents being notified and updated automatically. | Implemented
71-
[`State`](./behavioral/state.go) | Allow an object to alter its behavior when its internal state changes. The object will appear to change its class. | Implemented
72-
[`Strategy`](./behavioral/strategy.go) | Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. | Implemented
73-
[`Template Method`](./behavioral/template_method.go) | Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure. | Implemented
74-
[`Visitor`](./behavioral/visitor.go) | Represent an operation to be performed on the elements of an object structure. Visitor lets a new operation be defined without changing the classes of the elements on which it operates. | Implemented
62+
Name | Description
63+
-----------|-------------------------------------------
64+
[`Chain of Responsibility`](./behavioral/chain_of_responsibility.go) | Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.
65+
[`Command`](./behavioral/command.go) | Encapsulate a request as an object, thereby allowing for the parameterization of clients with different requests, and the queuing or logging of requests. It also allows for the support of undoable operations.
66+
[`Interpreter`](./behavioral/interpreter.go) | Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.
67+
[`Iterator`](./behavioral/iterator.go) | Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
68+
[`Mediator`](./behavioral/mediator.go) | Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it allows their interaction to vary independently.
69+
[`Memento`](./behavioral/memento.go) | Without violating encapsulation, capture and externalize an object's internal state allowing the object to be restored to this state later.
70+
[`Observer`](./behavioral/observer.go) | Define a one-to-many dependency between objects where a state change in one object results in all its dependents being notified and updated automatically.
71+
[`State`](./behavioral/state.go) | Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
72+
[`Strategy`](./behavioral/strategy.go) | Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
73+
[`Template Method`](./behavioral/template_method.go) | Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.
74+
[`Visitor`](./behavioral/visitor.go) | Represent an operation to be performed on the elements of an object structure. Visitor lets a new operation be defined without changing the classes of the elements on which it operates.
7575

7676
## Go Versions Supported
7777

behavioral/interpreter.go

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,117 @@
11
package behavioral
2+
3+
import (
4+
"strings"
5+
)
6+
7+
// Expression represents an expression to evaluate.
8+
type Expression interface {
9+
Interpret(variables *map[string]Expression) int
10+
}
11+
12+
// Integer represents an integer number.
13+
type Integer struct {
14+
integer int
15+
}
16+
17+
// Interpret returns the integer representation of the number.
18+
func (n *Integer) Interpret(variables *map[string]Expression) int {
19+
return n.integer
20+
}
21+
22+
// Plus represents the addition operation.
23+
type Plus struct {
24+
leftOperand Expression
25+
rightOperand Expression
26+
}
27+
28+
// Interpret interprets by adding the left and right variables.
29+
func (p *Plus) Interpret(variables *map[string]Expression) int {
30+
return p.leftOperand.Interpret(variables) + p.rightOperand.Interpret(variables)
31+
}
32+
33+
// Minus represents the substraction operation.
34+
type Minus struct {
35+
leftOperand Expression
36+
rightOperand Expression
37+
}
38+
39+
// Interpret interprets by subtracting the right from left variables.
40+
func (m *Minus) Interpret(variables *map[string]Expression) int {
41+
return m.leftOperand.Interpret(variables) - m.rightOperand.Interpret(variables)
42+
}
43+
44+
// Variable represents a variable.
45+
type Variable struct {
46+
name string
47+
}
48+
49+
// Interpret looks up the variable value and returns it, if not found returns zero.
50+
func (v *Variable) Interpret(variables *map[string]Expression) int {
51+
value, found := (*variables)[v.name]
52+
if found == false {
53+
return 0
54+
}
55+
return value.Interpret(variables)
56+
}
57+
58+
// Evaluator evaluates the expression.
59+
type Evaluator struct {
60+
syntaxTree Expression
61+
}
62+
63+
// NewEvaluator creates a new Evaluator.
64+
func NewEvaluator(expression string) *Evaluator {
65+
expressionStack := new(Stack)
66+
for _, token := range strings.Split(expression, " ") {
67+
if token == "+" {
68+
right := expressionStack.Pop().(Expression)
69+
left := expressionStack.Pop().(Expression)
70+
subExpression := &Plus{left, right}
71+
expressionStack.Push(subExpression)
72+
} else if token == "-" {
73+
right := expressionStack.Pop().(Expression)
74+
left := expressionStack.Pop().(Expression)
75+
subExpression := &Minus{left, right}
76+
expressionStack.Push(subExpression)
77+
} else {
78+
expressionStack.Push(&Variable{token})
79+
}
80+
}
81+
syntaxTree := expressionStack.Pop().(Expression)
82+
return &Evaluator{syntaxTree}
83+
}
84+
85+
// Interpret interprets the expression syntax tree.
86+
func (e *Evaluator) Interpret(context *map[string]Expression) int {
87+
return e.syntaxTree.Interpret(context)
88+
}
89+
90+
// Node represents a node in the stack.
91+
type Node struct {
92+
value interface{}
93+
next *Node
94+
}
95+
96+
// Stack represents a stack with push and pop operations.
97+
type Stack struct {
98+
top *Node
99+
size int
100+
}
101+
102+
// Push pushes a new value into the stack.
103+
func (s *Stack) Push(value interface{}) {
104+
s.top = &Node{value, s.top}
105+
s.size++
106+
}
107+
108+
// Pop pops a value out the stack.
109+
func (s *Stack) Pop() interface{} {
110+
if s.size == 0 {
111+
return nil
112+
}
113+
value := s.top.value
114+
s.top = s.top.next
115+
s.size--
116+
return value
117+
}

behavioral/interpreter_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package behavioral
2+
3+
import (
4+
"testing"
5+
6+
"github.com/stretchr/testify/assert"
7+
)
8+
9+
func TestInterpreter(t *testing.T) {
10+
expression := "w x z - +"
11+
sentence := NewEvaluator(expression)
12+
variables := make(map[string]Expression)
13+
variables["w"] = &Integer{5}
14+
variables["x"] = &Integer{10}
15+
variables["z"] = &Integer{42}
16+
result := sentence.Interpret(&variables)
17+
assert.Equal(t, -27, result)
18+
}

0 commit comments

Comments
 (0)