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]> 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