diff --git a/src/check_derivative.jl b/src/check_derivative.jl index c8762e0..a3a47ed 100644 --- a/src/check_derivative.jl +++ b/src/check_derivative.jl @@ -1,19 +1,19 @@ function check_derivative(f::Function, g::Function, x::Number) auto_g = derivative(f) - return max(abs(g(x) - auto_g(x))) + return maximum(abs(g(x) - auto_g(x))) end function check_gradient{T <: Number}(f::Function, g::Function, x::Vector{T}) auto_g = gradient(f) - return max(abs(g(x) - auto_g(x))) + return maximum(abs(g(x) - auto_g(x))) end function check_second_derivative(f::Function, h::Function, x::Number) auto_h = second_derivative(f) - return max(abs(h(x) - auto_h(x))) + return maximum(abs(h(x) - auto_h(x))) end function check_hessian{T <: Number}(f::Function, h::Function, x::Vector{T}) auto_h = hessian(f) - return max(abs(h(x) - auto_h(x))) + return maximum(abs(h(x) - auto_h(x))) end diff --git a/src/deparse.jl b/src/deparse.jl index 270cb55..64498af 100644 --- a/src/deparse.jl +++ b/src/deparse.jl @@ -1,24 +1,30 @@ +const infix_ops = [:+, :-, :*, :/, :^] +const op_priority = {:+ => 1, :- => 1, :* => 2, :/ => 2, :^ => 3} + +isinfix(ex::Expr) = ex.head == :call && ex.args[1] in infix_ops +isinfix(other) = false + function deparse(ex::Expr) if ex.head != :call return string(ex) - else - if ex.args[1] in [:+, :-, :*, :/, :^] - if length(ex.args) == 2 - return string(ex.args[1], deparse(ex.args[2])) - else - return join(map(x -> deparse(x), ex.args[2:end]), - string(" ", string(ex.args[1]), " ")) - end + end + op = ex.args[1] + args = ex.args[2:end] + if !(op in infix_ops) + return string(op, "(", join(map(deparse, args), ", "), ")") + end + if length(args) == 1 + return string(op, deparse(args[1])) + end + str = {} + for subexpr in args + if isinfix(subexpr) && op_priority[subexpr.args[1]] <= op_priority[op] + push!(str, string("(", deparse(subexpr), ")")) else - return string(ex.args[1], - "(", - join(map(x -> deparse(x), ex.args[2:end]), ", "), - ")") + push!(str, deparse(subexpr)) end end + return join(str, string(" ", string(op), " ")) end -deparse(other::Any) = string(other) -# TODO: Examine string contents of inputs, insert parentheses if added: -# + (CONTAINS * OR /) -# - (CONTAINS * OR /) +deparse(other) = string(other) diff --git a/test/deparse.jl b/test/deparse.jl index 869edb0..f0051d4 100644 --- a/test/deparse.jl +++ b/test/deparse.jl @@ -1,2 +1,8 @@ @assert isequal(deparse(:(cos(x) + sin(x))), "cos(x) + sin(x)") @assert isequal(deparse(:(cos(x) + sin(x) + exp(-x))), "cos(x) + sin(x) + exp(-x)") +@assert isequal(deparse(parse("x+y*z")), "x + y * z") +@assert isequal(deparse(parse("(x+y)*z")), "(x + y) * z") +@assert isequal(deparse(parse("1/(x/y)")), "1 / (x / y)") +@assert isequal(deparse(parse("1/(x*y)")), "1 / (x * y)") +@assert isequal(deparse(parse("z^(x+y)")), "z ^ (x + y)") +@assert isequal(deparse(parse("z^(x*y)")), "z ^ (x * y)")