我一直在玩python一段時間,並決定通過在python中編寫自定義腳本處理程序來更好地理解編程語言。到目前爲止,我已經成功地實現了一個基本的內存處理程序,並將內存地址座標掛接到屏幕上。我的問題可以這樣構成:使用非常基本的腳本實現函數
函數如何在這裏實現? goto聲明太簡單了,我想嘗試一些更困難的事情。 (編輯)最後,我希望能夠做到:
f0(x, y, z):=ax^by^cz
...在運行運行此模塊的腳本一個shell(傻了,是吧?)
# notes: separate addresses from data lest the loop of doom cometh
class Interpreter:
def __init__(self):
self.memory = { }
self.dictionary = {"mov" : self.mov,
"put" : self.put,
"add" : self.add,
"sub" : self.sub,
"clr" : self.clr,
"cpy" : self.cpy,
"ref" : self.ref }
self.hooks = {self.val("0") : self.out }
def interpret(self, line):
x = line.split(" ")
vals = tuple(self.val(y) for y in x[1:])
dereferenced = []
keys_only = tuple(key for key in self.memory)
for val in vals:
while val in self.memory: val = self.memory[val]
dereferenced.append(val)
vals = tuple(y for y in dereferenced)
self.dictionary[x[0]](vals)
def val(self, x):
return tuple(int(y) for y in str(x).split("."))
def mov(self, value):
self.ptr = value[0]
def put(self, value):
self.memory[self.ptr] = value[0]
def clr(self, value):
if self.ptr in self.hooks and self.ptr in self.memory:
x = self.hooks[self.ptr]
y = self.memory[self.ptr]
for z in y: x(z)
del self.memory[self.ptr]
def add(self, values):
self.put(self.mat(values, lambda x, y: x + y))
def sub(self, values):
self.put(self.mat(values, lambda x, y: x - y))
def mat(self, values, op):
a, b = self.memory[values[0]], self.memory[values[1]]
if len(a) > len(b): a, b = b, a
c = [op(a[x], b[x]) for x in xrange(len(b))] + [x for x in a[len(a):]]
return [tuple(x for x in c)]
def cpy(self, value):
self.put(value)
def out(self, x):
print chr(x),
def ref(self, x):
self.put(x)
interp = Interpreter()
for x in file(__file__.split('/')[-1].split(".")[-2] + ".why"):
interp.interpret(x.strip())
一個示例腳本:
mov 1
put 104.101.108.108.111.10
mov 0
ref 1
clr 0
(編輯)我已經決定使用這個嘗試作爲靈感,並從頭開始這個項目。 (希望我會找到一些真正的時間坐下來,再次開始課程之前編碼。)
我打算在幾天內授予最佳答案
。我希望這些信息不能阻止潛在的貢獻者提交任何他們覺得對這類編碼問題有用的東西。
我認爲你需要更具體一點,那就是「基本輸入/輸出功能」,但基本上它看起來像你可以做任何事情,就像你做其他事情一樣......也就是說,添加一個或多個命令到您的解釋器。 – martineau 2011-06-17 10:19:48
我用一個更好(更具體)的問題替換了這個問題。 – motoku 2011-06-17 10:28:56
@ Sean Pedersen如果你展示它應該如何表現(一些真實的動作測試,通過或失敗),它會更容易回答。 – DrTyrsa 2011-06-17 10:38:00