summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authormo khan <mo@mokhan.ca>2025-01-23 10:22:08 -0700
committermo khan <mo@mokhan.ca>2025-01-23 10:22:08 -0700
commit7031e53d352b3b8cb7e9e403a48818ff585b6bc2 (patch)
treec20a098be054aac19413e37c3fff385929d1c555
parent69030c3e15ff79b1a2b40b97a2c418f6b3474697 (diff)
Complete question from chapter 11.
-rw-r--r--3431709-assignment-4.pdfbin143403 -> 148455 bytes
-rw-r--r--assignments/4-solution.md45
-rwxr-xr-xassignments/4/tokenizer.rb25
3 files changed, 70 insertions, 0 deletions
diff --git a/3431709-assignment-4.pdf b/3431709-assignment-4.pdf
index 2c4cf32..e30a341 100644
--- a/3431709-assignment-4.pdf
+++ b/3431709-assignment-4.pdf
Binary files differ
diff --git a/assignments/4-solution.md b/assignments/4-solution.md
index 43c7781..4a75011 100644
--- a/assignments/4-solution.md
+++ b/assignments/4-solution.md
@@ -21,4 +21,49 @@ first is bigger
Chapter 11:
+Figure 11.9
+
+1. Identify the tokens in each of the following statements. (You do not need to classify them; just identify them.)
+ a. `if (a == b1) a = x + y;`
+
+ | token | type |
+ | ----- | ---- |
+ | if | if condition |
+ | ( | left paren |
+ | a | symbol |
+ | == | comparison operator |
+ | b1 | symbol |
+ | a | symbol |
+ | = | assignment operator |
+ | x | symbol |
+ | + | addition operator |
+ | y | symbol |
+ | ; | statement terminator |
+
+ b. `delta = epsilon + 1.23 - sqrt(zz);`
+
+ | token | type |
+ | ----- | ---- |
+ | delta | symbol |
+ | = | assignment operator |
+ | epsilon | symbol |
+ | + | addition operator |
+ | 1.23 | floating point number |
+ | - | subtraction operator |
+ | sqrt | symbol |
+ | ( | left paren |
+ | zz | symbol |
+ | ) | right paren |
+ | ; | statement terminator |
+
+ c. `print(Q);`
+
+ | token | type |
+ | ----- | ---- |
+ | print | symbol |
+ | ( | left paren |
+ | Q | symbol |
+ | ) | right paren |
+ | ; | statement terminator |
+
Chapter 12:
diff --git a/assignments/4/tokenizer.rb b/assignments/4/tokenizer.rb
new file mode 100755
index 0000000..0bd2e2d
--- /dev/null
+++ b/assignments/4/tokenizer.rb
@@ -0,0 +1,25 @@
+#!/usr/bin/env ruby
+
+WHITESPACE = Regexp.new('[[:blank:]]+')
+SPLITTABLES = [';', '(', ')']
+
+def tokenize(code)
+ pattern = Regexp.new("[^#{Regexp.escape(SPLITTABLES.join)}]+")
+ output = []
+ tokens = code.chomp.strip.split(WHITESPACE)
+ tokens.each do |token|
+ prefix, stem, suffix = token.partition(pattern)
+ output << prefix.split('') unless prefix.empty?
+ output << stem unless stem.empty?
+ output << suffix.split('') unless suffix.empty?
+ end
+
+ output.flatten
+end
+
+
+code = ARGV[0]
+tokens = tokenize(code)
+
+puts "Input: #{code.inspect}"
+puts "Tokens: #{tokens.inspect}"