jw3126
April 4, 2019, 11:33am
1
Currently a struct definition returns nothing
:
julia> x = struct Foo end
julia> x === nothing
true
How about it returning the defined type instead?
julia> x = struct Foo end
julia> x === Foo
true
Why would this behaviour be useful? It would make the following pattern to “redefine types” more convenient:
Foo = struct Foo1
field1
end
function doit(foo::Foo)
foo.field1 + foo.field2
end
Now we can simply edit the above without restarting julia and it will work:
Foo = struct Foo2{T <: Number}
field1::T
field2::T
end
function doit(foo::Foo)
foo.field1 + foo.field2
end
Or even
Foo = @eval struct $(gensym())
field1
field2
end
1 Like
I don’t think we should introduce a language future just to work around the issues addressed by
JuliaLang:master
← JuliaLang:teh/type_redefinition
opened 11:56AM - 09 Jul 17 UTC
Several of us have found [Revise.jl](https://github.com/timholy/Revise.jl) to be… a significant productivity booster. In principle, it's now possible to keep a Julia session open for a week or more, at which point one of the main negatives of Julia---the cost of JITting your, e.g., plotting package---becomes a non-issue.
However, there are two events which prevent this from being commonplace. One is method-deletion (#20048) and the other is type redefinition (https://github.com/timholy/Revise.jl/issues/18). It occurred to me that type redefinition may not be quite as nasty a problem as I've thought. A demo with this PR:
```julia
julia> struct Mine
arg
end
julia> a = Mine(1)
Mine(1)
julia> foo(val::Mine) = val.arg
foo (generic function with 1 method)
julia> Base.shunt_binding(Main, :Mine)
Mine#1
julia> a
Mine#1(1)
julia> foo(a)
1
julia> struct Mine{T}
arg::T
end
julia> x = Mine(3)
Mine{Int64}(3)
```
The only catch I'm aware of is:
```julia
julia> foo(x)
ERROR: MethodError: no method matching foo(::Mine{Int64})
Closest candidates are:
foo(::Mine#1) at REPL[3]:1
```
However, I wonder if this might be solvable via `methodswith` *plus* maintaining a cache of the source-code expressions so that they can be re-evaluated. (Revise would like that anyway, since it re-parses and caches every source file so that it can detect diffs. This adds considerably to the package load time, but caching the Exprs to the `.ji` file seems both cheap and effective.)
2 Likes
jw3126
April 4, 2019, 1:40pm
3
I agree that one should not introduce language features just to hack around other limitations. However this one is also natural and consistent. For instance function definitions return the definied function.
It’s actually pretty reasonable for a type definition to return the type that’s defined though. The main reason we don’t do that is because printing the type in the REPL after it’s defined is a bit annoying. Returning the type would be more lispy.
1 Like