Created
October 12, 2015 00:20
-
-
Save gulan/0f31e0272f531a6e5f89 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| Arrange a program as a dictionary where the keys are program labels | |
| and the bodies are python code. The idea is to let python do | |
| computation, but let me define flow-control and means of program | |
| composition. | |
| This is a simple program, so I stick to simple Python. | |
| """ | |
| from collections import namedtuple | |
| CodeBody = namedtuple('CodeBody','label code') | |
| class State(dict): | |
| # Like a dict, except I can write d.x instead of d['x'] | |
| def __getattr__(self,name): | |
| return self[name] | |
| def __setattr__(self,name,value): | |
| self[name] = value | |
| def link_program(cblist): | |
| program = {} | |
| for cb in cblist: | |
| program[cb.label] = cb.code | |
| return program | |
| def run_program(program,state): | |
| state.pc = 'start' # pc is short for 'program counter' | |
| while state.pc != 'EXIT': | |
| print 'Trace>', state | |
| routine = program[state.pc] | |
| routine(state) | |
| # ##### example ##### | |
| def example(): | |
| # print sum of 0..9 | |
| i = 0 | |
| s = 0 | |
| while i < 10: | |
| s += i | |
| i += 1 | |
| print s | |
| """ | |
| If I had a compiler I could generate assembly-like code. | |
| compile(example) would generate: | |
| start: | |
| i = 0 | |
| s = 0 | |
| while-guard: | |
| goto while-end, unless i < 10 | |
| while-body: | |
| s += i | |
| i += 1 | |
| goto while-guard | |
| while-end: | |
| print s | |
| """ | |
| # Python has no way to make anonymous code blocks, so I need to | |
| # define some functions: | |
| def _start(state): | |
| state.i = 0 | |
| state.s = 0 | |
| state.pc = 'while-guard' | |
| def _while_guard(state): | |
| state.pc = 'while-body' if state.i < 10 else 'while-end' | |
| def _while_body(state): | |
| state.s += state.i | |
| state.i += 1 | |
| state.pc = 'while-guard' | |
| def _while_end(state): | |
| print state.s | |
| state.pc = 'EXIT' | |
| p1 = CodeBody('start',_start) | |
| p2 = CodeBody('while-guard',_while_guard) | |
| p3 = CodeBody('while-body',_while_body) | |
| p4 = CodeBody('while-end',_while_end) | |
| prog = link_program([p1,p2,p3,p4]) | |
| run_program(prog,State()) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment