Using an array of abstract types in Julia

I study Julia, so I'm a beginner. Now I am studying its strongly typed functions. I understand that I do not see the use of abstract types for arrays. Let me explain with an example:

Suppose I would like to create a function that accepts arrays of reals, regardless of their specific type. I would use:

function f(x::Array{Real}) # do something end 

This function can never be called without raising a f has no method matching f(::Array{Float64,1})

I would call f([1,2,3]) or f([1.,2.,3.]) , While the element type is Real.

I read that you can promote or convert an array (p.eg f(convert(Array{Real}, [1, 2, 3])) or so), but I see that it is really non-dynamic and tedious.

Is there any other alternative, rather than getting rid of strongly typed behavior?

Thanks.

+5
source share
2 answers

To extend @ user3580870's solution , you can also use typealias to make the function definition a bit more concise:

 typealias RealArray{T<:Real} Array{T} f(x::RealArray) = "do something with $x" 

And then you can also use typealias in anonymous functions:

 g = (x::RealArray) -> "something else with $x" 
+7
source

You can do this explicitly using the <: subtype operator :

 function f(x::Array) return zero.(x) end function f(x::Array{<:Real}) return one.(x) end @show f([1, 2]) @show f([1.0, 2.0]) @show f([1im, 2im]) 

seal

 f([1, 2]) = [1, 1] f([1.0, 2.0]) = [1.0, 1.0] f([1im, 2im]) = Complex{Int64}[0+0im, 0+0im] 
0
source

Source: https://habr.com/ru/post/1244188/


All Articles