如何解析以扁平整数列表呈现的嵌套函数结构?
嵌套函数扁平列表解析函数优化需求
我需要实现一个可靠且优雅的解析函数,用于处理以扁平列表形式呈现的嵌套函数结构。以下是简化示例说明问题:
['foo', 1, 'a', 'foo', 2, 'foo', 1, 'b', 'foo', -1, 'foo', -1, "bar", 1, "c", "bar", 2, 'baz', 1, 'd', 'baz', -1, "bar", 3, "e", "bar", 4, 'qux', 1, 'stu', 1, 'f', 'stu', -1, 'qux', -1, 'bar', -1]
(用"stu"是因为占位符名称用完了。)
核心规则说明
- 字符串为函数名,函数名后的数字表示后续参数在函数中的位置,
-1用于关闭函数。 - 基础示例:
['foo',1,'a','foo',2,'b','foo',-1]等价于foo('a', 'b') - 嵌套示例:
['foo', 1, 'a', 'foo', 2, 'foo', 1, 'b', 'foo', -1, 'foo', -1]等价于foo('a', foo('b'))
期望输出格式
输入:
['foo', 1, 'a', 'foo', 2, 'foo', 1, 'b', 'foo', -1, 'foo', -1, 'bar', 1, 'c', 'bar', -1]
应返回:
[['foo', 'a', ['foo', 'b']], ['bar', 'c']]
实际场景细节
实际场景中列表所有元素均为整数,函数名是三个整数的序列。例如简化示例中的['foo',1,'a','foo',2,'b','foo',-1]对应实际序列:
[1, 1, 1, 1, 104, 1, 1, 1, 2, 105, 1, 1, 1, -1]
函数名对应constructs字典的键,字典示例如下:
constructs = { 1: { 1: { 1: lambda *chars : print(''.join(chr(char) for char in chars)) } } }
解析结果应类似:
[[lambda *chars : print(''.join(chr(char) for char in chars)), 104, 105]]
额外规则
- 0需被忽略跳过
- 若0跟随函数调用,则该函数调用需被视为参数而非函数
现有实现问题
我现有实现代码如下,但无法处理同函数嵌套的情况,且存在效率和优雅性问题:
constructs = { 1: { 1: { 1: print, } } } def parse(code: list) -> list: if len(code) <= 1: return code result = [] in_function = 0 for i, token in enumerate(code): if in_function > 0: in_function -= 1 continue if token == 0: continue if result and result[-1][0][3] != -1: if token in constructs and code[i + 1] in constructs[token] and code[i + 2] in constructs[token][code[i + 1]]: if i < len(code) - 4 and code[i + 4] == 0: result[-1][-1].append(token) else: if code[i + 3] == result[-1][0][3] + 1: result[-1].append([]) result[-1][0] = code[i:i + 4] in_function = 3 else: result[-1][-1].append(token) else: if token in constructs and code[i + 1] in constructs[token] and code[i + 2] in constructs[token][code[i + 1]]: if code[i + 3] == 1: result.append([code[i:i + 4], []]) in_function = 3 else: raise SyntaxError(f'function {code[i:i + 3]} has no previous separator {code[i + 3] - 1}') else: raise SyntaxError(f'function {code[i:i + 3]} was not recognized') for i, function in enumerate(result): result[i][0] = constructs[result[i][0][0]][result[i][0][1]][result[i][0][2]] for j, argument in enumerate(result[i][1:]): result[i][j + 1] = parse(argument) return result
该代码可处理:
parse([1, 1, 1, 1, 'Hello world', 1, 1, 1, 2, 'etc', 1, 1, 1, -1])
但无法处理:
parse([1, 1, 1, 1, 1, 1, 1, 1, 'Hello world', 1, 1, 1, -1, 1, 1, 1, 2, 'etc', 1, 1, 1, -1])
寻求优化实现方案。
内容的提问来源于stack exchange,提问作者Eric Wang
相关产品推荐
相关产品推荐

