Hacker News new | ask | show | jobs
by cloudkj 2409 days ago
Coincidentally, I just wrote a simple JSON parser the other day as a toy exercise. A simplified snippet of parsing code (handling only arrays) relevant to the discussion here would be something like:

  def parse(text):
      stack = []
      index = 0
      result = None
      while index < len(text):
          char = text[index]
          val = None
          if char == '[':
              stack.append([])
          elif char == ']':
              val = stack.pop()
          index += 1
          if val is not None:
              if stack:
                  stack[-1].append(val)
              else:
                  result = val
      return result
Using the test utilities in the repo indicate that the parsing logic can handle arbitrarily nested arrays (e.g. up to the 5,000,000 max in the test script), bound by the limits of the heap.

It seems like the main criticism here is against recursive implementations. Or am I missing something?

1 comments

A better question to ask is: Is it a success of CS education since developers know when to make tradeoffs in software engineering and go for the most easily understandable code (recursive implementation used in most pseudo code) since deeply recursive cases are rare, or is it a failure that software engineers cannot figure out how to convert a recursive algorithm into an iterative implementation for greater memory efficiency?
It doesn't necessarily mean anything that deeply nested cases are rare. If you're making a general library, someone is going to throw user input at it, and some users will try to break your system. If it can avoid a crash in that case, it usually should.