Design Pattern Examples
Overview of object-oriented design patterns
Interpreter_Exercise.cs
Go to the documentation of this file.
1
5
6using System;
7using System.Collections.Generic;
8using System.Linq;
9using System.Text;
10using System.Threading.Tasks;
11
13{
31 internal class Interpreter_Exercise
32 {
33
39 string _TokensToString(int[] tokens)
40 {
41 StringBuilder output = new StringBuilder();
42
43 output.Append("[");
44 for (int index = 0; index < tokens.Length; ++index)
45 {
46 output.AppendFormat("{0,3}", tokens[index]);
47 if (index + 1 < tokens.Length)
48 {
49 output.Append(", ");
50 }
51 }
52 output.Append("]");
53 return output.ToString();
54 }
55
56
63 static int[][] _sentenceTokenLists = new int[][] {
64 new int[] { 39, 18, 17, 27, 2, 7, 101 }, // "What do you say to that?"
65 new int[] { 32, 17, 1, 0, 34, 2, 1, 37, 101 }, // "Will you be the one to be there?"
66 new int[] { 36, 17, 8, 5, 32, 2, 18, 7, 101 }, // "Would you have a will to do that?"
67 new int[] { 11, 12, 17, 9, 36, 12, 1, 6, 20, 100 }, // "For not you I would not be in this."
68 new int[] { 26, 27, 7, 21, 36, 17, 27, 10, 101 }, // "We say that but would you say it?"
69 new int[] { 23, 28, 32, 26, 32, 18, 10, 100 } // "By her will we will do it."
70 };
71
75 // ! [Using Interpreter in C#]
76 public void Run()
77 {
78 Console.WriteLine();
79 Console.WriteLine("Interpreter Exercise");
80
81 Interpreter_Class interpreter = new Interpreter_Class();
82
83 for (int sentenceIndex = 0; sentenceIndex < _sentenceTokenLists.Length; ++sentenceIndex)
84 {
85 int[] tokenList = _sentenceTokenLists[sentenceIndex];
86
87 string tokensAsString = _TokensToString(tokenList);
88
89 string sentence = interpreter.Interpret(tokenList);
90
91 // 50 is a magic number corresponding to the longest token list
92 // expressed as a string. Derived empirically. It makes the
93 // output easier to, er, interpret.
94 Console.WriteLine(" {0,-50} ==> \"{1}\"", tokensAsString, sentence);
95 }
96 Console.WriteLine(" Done.");
97 }
98 // ! [Using Interpreter in C#]
99 }
100}
Representation of a simple interpreter.
string Interpret(int[] tokens)
Given an array of integer tokens, convert the tokens into a single string of space-delimited words,...
Example of using the Interpreter Pattern in C#.
string _TokensToString(int[] tokens)
Helper method to convert a list of ints to a string representation.
static int[][] _sentenceTokenLists
A list of pre-defined token lists. Each token list represents a single sentence constructed from the ...
void Run()
Executes the example for the Interpreter Pattern in C#.
The namespace containing all Design Pattern Examples implemented in C#.