Matching parentheses algorithm in immutable/pure functional Scala with foldLeft and a finite-state machine