More improvements to forth style

This commit is contained in:
Crista Lopes
2013-11-07 13:00:28 -08:00
parent e5e5805e7c
commit 0707ba6a64

View File

@@ -73,19 +73,21 @@ def frequencies():
heap['word_list'] = stack.pop()
heap['word_freqs'] = {}
# A little flavour of the real Forth style here...
stack.append(0) # Counter of words at stack[0]
stack.append(0) # Counter of words, at stack[0]
while stack[-1] != len(heap['word_list']):
stack.append(heap['word_list'][stack[-1]]) # Push the word, stack[1]
# ... but the following line is not in style, because the naive implementation
# would be too slow, or we'd need to implement faster, hash-based search
if stack[-1] in heap['word_freqs']:
stack.append(heap['word_freqs'][stack[1]]) # push the frequency, stack[2]
stack[2] = stack[2] + 1 # Swap the tuple the stack with a new one
# Increment the frequency, postfix style: f 1 +
stack.append(heap['word_freqs'][stack[1]]) # push the frequency
stack.append(1) # push 1
stack.append(stack.pop() + stack.pop()) # add
else:
stack.append(1) # Push 1 in stack[2]
heap['word_freqs'][stack.pop()] = stack.pop() # Load the updated freq back onto the heap
# Increment the counter
# Increment the counter, postfix style
stack.append(1)
stack.append(stack.pop() + stack.pop()) # Add the operands on the stack
# Done with iteration. Pop the counter