For your "additional" question: no overhead for the abstract version versus 
the two specialized. Don't think of them as types like in C/C++ function 
definition, think of them as a filter. Julia will compile a new version for 
every type input you put in anyway that is specialized for the type parsed 
in.

On Tuesday, July 8, 2014 2:51:41 PM UTC-7, John Myles White wrote:
>
> What you're doing isn't a workaround: it's the correct way to do this in 
> the current version of Julia. There may be shorthand in the future, but 
> this is the right approach today. 
>
>  -- John 
>
> On Jul 8, 2014, at 2:01 PM, Andrei Zh <[email protected] <javascript:>> 
> wrote: 
>
> > Here's another question about code style. Let's say I want to write 
> function "inc()" that just adds 1 to its (typed) argument. For simple 
> numbers I can force parameter to be of type Number: 
> > 
> >   julia> function inc(x::Number) x + 1 end 
> >   inc (generic function with 1 method) 
> > 
> >   julia> inc(1) 
> >   2 
> > 
> >   julia> inc(1.) 
> >   2.0 
> > 
> > For parametrised collections, however, it doesn't work, since Julia's 
> type parameters are invariant: 
> > 
> >   julia> function inc(x::Vector{Number}) x + 1 end 
> >   inc (generic function with 2 methods) 
> > 
> >   julia> inc([1, 2]) 
> >   ERROR: no method inc(Array{Int64,1}) 
> > 
> >   julia> inc([1., 2.]) 
> >   ERROR: no method inc(Array{Float64,1}) 
> > 
> > As a workaround I use parametrized functions, which work just fine: 
> > 
> >   julia> function inc{T <: Number}(x::Vector{T}) x + 1 end 
> >   inc (generic function with 3 methods) 
> > 
> >   julia> inc([1, 2]) 
> >   2-element Array{Int64,1}: 
> >    2 
> >    3 
> > 
> >   julia> inc([1., 2.]) 
> >   2-element Array{Float64,1}: 
> >    2.0 
> >    3.0 
> > 
> > But since operations on vectors of (any) numbers are so common, I would 
> expect simpler / shorter way to write them. More generally, I wonder if 
> there's a better way to write functions with collections parametrized by 
> abstract classes. 
> > 
> > Additional (but closely related) question: is there any run-time 
> overhead for function arguments with abstract type parameters over several 
> functions with concrete types? E.g. is writing "inc(x::Vector{Int})" and 
> "inc(x::Vector{Float64})" faster than "function inc{T <: 
> Number}(x::Vector{T})"? 
>
>

Reply via email to