From 3c276c0913140d76f41b213359c00dbedf861406 Mon Sep 17 00:00:00 2001 From: Simon Forman Date: Thu, 11 Apr 2024 11:01:14 -0700 Subject: [PATCH] Reverse tokens instead of temp lists. This way we can build the tuples representing the Thun lists as we go and I bet it's more efficient, eh? --- implementations/Python/joy.py | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/implementations/Python/joy.py b/implementations/Python/joy.py index a8ddccf..7eb991f 100644 --- a/implementations/Python/joy.py +++ b/implementations/Python/joy.py @@ -349,22 +349,21 @@ def text_to_expression(text): :rtype: stack :raises ParseError: if the parse fails. ''' - frame = [] - stack = [] + lists = [] + stack = () - for tok in text.replace('[', ' [ ').replace(']', ' ] ').split(): + for tok in reversed(text.replace('[', ' [ ').replace(']', ' ] ').split()): if tok == '[': - stack.append(frame) - frame = [] + if not lists: + raise ParseError('Unclosed bracket.') + thing, stack = stack, lists.pop() + + elif tok == ']': + lists.append(stack) + stack = () continue - if tok == ']': - thing = list_to_stack(frame) - try: - frame = stack.pop() - except IndexError: - raise ParseError('Extra closing bracket.') from None elif tok == _T: thing = True elif tok == _F: @@ -375,12 +374,12 @@ def text_to_expression(text): except ValueError: thing = Symbol(tok) - frame.append(thing) + stack = thing, stack - if stack: - raise ParseError('Unclosed bracket.') + if lists: + raise ParseError('Extra closing bracket.') - return list_to_stack(frame) + return stack '''