|
| 1 | +const infix_ops = [:+, :-, :*, :/, :^] |
| 2 | +const op_priority = {:+ => 1, :- => 1, :* => 2, :/ => 2, :^ => 3} |
| 3 | + |
| 4 | +isinfix(ex::Expr) = ex.head == :call && ex.args[1] in infix_ops |
| 5 | +isinfix(other) = false |
| 6 | + |
1 | 7 | function deparse(ex::Expr) |
2 | 8 | if ex.head != :call |
3 | 9 | return string(ex) |
4 | | - else |
5 | | - if ex.args[1] in [:+, :-, :*, :/, :^] |
6 | | - if length(ex.args) == 2 |
7 | | - return string(ex.args[1], deparse(ex.args[2])) |
8 | | - else |
9 | | - return join(map(x -> deparse(x), ex.args[2:end]), |
10 | | - string(" ", string(ex.args[1]), " ")) |
11 | | - end |
| 10 | + end |
| 11 | + op = ex.args[1] |
| 12 | + args = ex.args[2:end] |
| 13 | + if !(op in infix_ops) |
| 14 | + return string(op, "(", join(map(x -> deparse(x), args), ", "), ")") |
| 15 | + end |
| 16 | + if length(args) == 1 |
| 17 | + return string(op, deparse(args[1])) |
| 18 | + end |
| 19 | + str = {} |
| 20 | + for subexpr in args |
| 21 | + if isinfix(subexpr) && op_priority[subexpr.args[1]] <= op_priority[op] |
| 22 | + push!(str, string("(", deparse(subexpr), ")")) |
12 | 23 | else |
13 | | - return string(ex.args[1], |
14 | | - "(", |
15 | | - join(map(x -> deparse(x), ex.args[2:end]), ", "), |
16 | | - ")") |
| 24 | + push!(str, deparse(subexpr)) |
17 | 25 | end |
18 | 26 | end |
| 27 | + return join(str, string(" ", string(op), " ")) |
19 | 28 | end |
20 | | -deparse(other::Any) = string(other) |
21 | 29 |
|
22 | | -# TODO: Examine string contents of inputs, insert parentheses if added: |
23 | | -# + (CONTAINS * OR /) |
24 | | -# - (CONTAINS * OR /) |
| 30 | +deparse(other) = string(other) |
0 commit comments