bench-rejected-impls/18_operation_order.rb
# Guess I didn't think of doing it this way at the time (do the parentheses first...)
Guess I didn't think of doing it this way at the time (do the parentheses first...)
Guess I didn ' t think of doing it this way at the time ( do the parentheses first ... )
def string_replacement_add_before_mul2(expr, depth = 0, verbose: false)
  expr = expr.delete(' ') if depth == 0
  lpad = '    ' * depth
  while (rparen = expr.index(?)))
    lparen = expr.rindex(?(, rparen)
    replace = expr[(lparen + 1)...rparen]
    replacement = string_replacement_add_before_mul2(replace, depth + 1, verbose: verbose)
    expr[lparen..rparen] = replacement.to_s
    puts "#{lpad}#{replace} = #{replacement}, now #{expr}" if verbose
  end
  while (add = expr[/(\d+)\+(\d+)/])
    expr[add] = v = (Integer($1) + Integer($2)).to_s
    puts "#{lpad}#$1 + #$2 = #{v}; now #{expr}" if verbose
  end
  while (mul = expr[/(\d+)\*(\d+)/])
    expr[mul] = v = (Integer($1) * Integer($2)).to_s
    puts "#{lpad}#$1 * #$2 = #{v}; now #{expr}" if verbose
  end
  Integer(expr)
end
def string_replacement_add_before_mul2 ( expr , depth = 0 , verbose : false ) expr = expr . delete ( ' ' ) if depth == 0 lpad = '    ' * depth while ( rparen = expr . index ( ?) ) ) lparen = expr . rindex ( ?( , rparen ) replace = expr [ ( lparen + 1 ) ... rparen ] replacement = string_replacement_add_before_mul2 ( replace , depth + 1 , verbose : verbose ) expr [ lparen .. rparen ] = replacement . to_s puts "#{lpad}#{replace} = #{replacement}, now #{expr}" if verbose end while ( add = expr [ / ( \d +) \+ ( \d +) / ] ) expr [ add ] = v = ( Integer ( $1 ) + Integer ( $2 ) ) . to_s puts "#{lpad}#$1 + #$2 = #{v}; now #{expr}" if verbose end while ( mul = expr [ / ( \d +) \* ( \d +) / ] ) expr [ mul ] = v = ( Integer ( $1 ) * Integer ( $2 ) ) . to_s puts "#{lpad}#$1 * #$2 = #{v}; now #{expr}" if verbose end Integer ( expr ) end
Guess I didn't think of doing it this way at the time (do the parentheses first...)
Guess I didn ' t think of doing it this way at the time ( do the parentheses first ... )
# Looking forward from the first left parenthesis is prone to nesting problems like ((1 + 2) + 3) # Looking backward from the first right parenthesis, though, is totally fine.
expr
<not_specific>
depth
<not_specific>
verbose
<not_specific>