Skip to content

Instantly share code, notes, and snippets.

@kmsquire
Last active December 27, 2015 23:39
Show Gist options
  • Save kmsquire/7407973 to your computer and use it in GitHub Desktop.
Save kmsquire/7407973 to your computer and use it in GitHub Desktop.
Create infix string from Julia expression
let ops_prec = (Symbol=>Int)[], prec=0, _op_str, _op, tight
ops_by_prec = ["= := += -= *= /= //= .//= .*= ./= \\= .\\= ^= .^= %= .%= |= &= \$= => <<= >>= >>>= ~ .+= .-=",
"?",
"||",
"&&",
"-- -->",
"> < >= <= == === != !== .> .< .>= .<= .== .!= .= .! <: >:",
"|> <|",
": ..",
"+ - .+ .- | \$",
"<< >> >>> .<< .>> .>>>",
"* / ./ % .% & .* \\ .\\",
"// .//",
"^ .^",
"::",
"."]
global infix
for _op_str in ops_by_prec
prec += 1
for _op in split(_op_str)
ops_prec[symbol(_op)] = prec
end
end
const tight = ops_prec[:(^)]
function infix(x::Expr, prec = 0)
if x.head != :call
return string(x)
end
op = x.args[1]
args = x.args[2:end]
op_prec = get(ops_prec, op, 0)
local ret
if op_prec == 0
infargs = join([infix(arg) for arg in args], " ,")
ret = "$op($infargs)"
elseif op == :(*) && length(args)==2 && isa(args[1], Real) && !isa(args[2], Real)
m1 = args[1]
m2 = infix(args[2])
ret = "$m1$m2"
else
ops = op_prec < tight ? " $op " : "$op"
ret = join([infix(arg, op_prec) for arg in args], ops)
if op_prec <= prec
ret = "($ret_str)"
end
end
ret
end
infix(x, prec = 0) = string(x)
end
julia> include("infix.jl")
infix (generic function with 4 methods)
julia> ex = :(sqrt(sin(2pi*x)^2+cos(2pi*x)^2))
:(sqrt(+(^(sin(*(*(2,pi),x)),2),^(cos(*(*(2,pi),x)),2))))
julia> infix(ex)
"sqrt(sin(2pi * x)^2 + cos(2pi * x)^2)"
julia> a = :(5+2b)
:(+(5,*(2,b)))
julia> infix(a)
"5 + 2b"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment