使用非常基本的脚本实现功能

mot*_*oku 17 python programming-languages

我已经玩了一段时间的python,并决定通过在python中编写自定义脚本处理程序来更好地理解编程语言.到目前为止,我已成功实现了一个基本的内存处理程序,并将一个内存地址坐标挂钩到打印到屏幕上.我的问题可以提出如下:

如何在这里实现功能?goto声明太容易了,我想尝试更难的事情.(编辑)最终我希望能够做到:

f0(x, y, z):=ax^by^cz
Run Code Online (Sandbox Code Playgroud)

...在运行该模块的脚本的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())
Run Code Online (Sandbox Code Playgroud)

示例脚本:

mov 1
put 104.101.108.108.111.10
mov 0
ref 1
clr 0
Run Code Online (Sandbox Code Playgroud)

(编辑)我决定用这个尝试作为灵感,并从头开始这个项目.(希望我能在课程开始之前找到一些实时坐下来编写代码.)我打算在几天内给出最好的答案.我希望这些信息无法阻止潜在的贡献者提交他们认为对这种编码问题有帮助的任何内容.

mac*_*mac 3

我有点难以理解你在问什么。你的函数定义在哪里给出?在脚本处理程序中还是在脚本中?

如果它在脚本处理程序中,显而易见的解决方案是使用表达式lambda。使用您在问题中使用的示例f0(x, y, z):=x^2将翻译为:

>>> f0 = lambda x, y, z : x**2
>>> f0(2,3,4)
4
Run Code Online (Sandbox Code Playgroud)

如果要将函数定义放在脚本本身中,则可以使用lambdaeval表达式的组合。这是我刚刚拼凑在一起的一个简单示例来说明这个想法。

class ScriptParser(object):

    # See 'to_python' to check out what this does
    mapping = {'^':'**', '!':' not ', '&':' and '}

    def to_python(self, calc):
        '''
        Parse the calculation syntax from the script grammar to the python one.
        This could be grown to a more complex parser, if needed. For now it will
        simply assume any operator as defined in the grammar used for the script
        has an equivalent in python.
        '''
        for k, v in self.mapping.items():
            calc = calc.replace(k, v)
        return calc

    def feed(self, lfs):
        '''
        Parse a line of the script containing a function defintion
        '''
        signature, calc = lfs.split(':=')
        funcname, variables = [s.strip() for s in signature.split('(')]
        # as we stripped the strings, it's now safe to do...'
        variables = variables[:-1]
        setattr(self, funcname,
                eval('lambda ' + variables + ' : ' + self.to_python(calc)))

def main():
    lines = ['f0(x, y, z) := x^2',
             'f1(x) := x**2 + x**3 + x*1000']
    sp = ScriptParser()
    for line in lines:
        sp.feed(line)
        print('Script definition  : %s' % line)
    for i in range(5):
        res0 = sp.f0(i, None, None)
        res1 = sp.f1(i)
        print('f0(%d) = %d' % (i, res0))
        print('f1(%d) = %d' % (i, res1))
        print('--------')

if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

运行该程序输出:

Script definition  : f0(x, y, z) := x^2
Script definition  : f1(x) := x**2 + x**3 + x*1000
f0(0) = 0
f1(0) = 0
--------
f0(1) = 1
f1(1) = 1002
--------
f0(2) = 4
f1(2) = 2012
--------
f0(3) = 9
f1(3) = 3036
--------
f0(4) = 16
f1(4) = 4080
--------
Run Code Online (Sandbox Code Playgroud)

但请记住:

  1. 使用eval具有您应该注意的安全隐患。
  2. 编写自己的语法解析器是一次非常酷的学习体验!:)

HTH,麦克。