Interesting Eval Problem

Hi guys,
I am having a incorrect eval result. Can you help me with this?


    type EE
        x::Int
    end

    type DD
        x::Float64
        y::EE
    end

   ex = quote
           x = $(Expr(:new, Int64, 1))
           x += $(Expr(:new, Int64, 2)) 
           y = x - $(Expr(:new, Int64, 1)) 
           $(Expr(:new, DD, :(x + y), :($(Expr(:new, EE, :y)))))
    end

   eval(ex)

the result seems to be:

DD(2.5e-323,EE(2))
  • Why are you using new?
  • But more importantly, what exactly are you trying to do? eval is rarely the correct answer.
1 Like
begin 
     x=1
     x+=2
     y=x-1
     DD(x+y,EE(y)) 
end

I manually translated the code above to Exprs with :new and I am trying to understand why it doesn’t give me the right answer.
Thanks

Why are you using new at all though? (I mean, where did that come from.)

:new is a way to create DataType like Int, Float64, user defined types and so on. I always liked using new while creating a user defined type rather than call.
What is wrong about it?

I have never seen new used like that, except in the one particular case of so-called “inner constructors” for user-defined types.

It is unnecessary and redundant.

Thank you for your insight, but still no reason why it is wrong.
And the eval is irrelevant, you can use a macro to return the expression i wrote. It will give you the same wrong result.

See the manual on :new:

Allocates a new struct-like object. First argument is the type. The new pseudo-function is lowered to this, and the type is always inserted by the compiler. This is very much an internal-only feature, and does no checking. Evaluating arbitrary new expressions can easily segfault.

Chances are you should not be using this. Would an expression equivalent to

DD(x + y, EE(y))

do what you want? You can construct those very easily. But knowing more about the context (ie what you are trying to do, already asked by @dpsanders) would allow people to help you better.

2 Likes

FWIW, if you do this

ex = quote
       x = $(Expr(:new, Int64, 1))
       x += $(Expr(:new, Int64, 2)) 
       y = x - $(Expr(:new, Int64, 1)) 
       $(Expr(:new, DD, :(Float64(x + y)), :($(Expr(:new, EE, :y)))))
end

it works as expected.

julia> reinterpret(Float64, 5)
2.5e-323
1 Like

Thank you all!
You have been greatly helpful.