Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of Array of abstract types in Julia

I'm exploring Julia so I'm a newbie. Now I'm exploring its strongly typed features. What I'm realizing is that I can't see the usage of abstract types for arrays. Let me explain with an example:

Let's suppose that I would like to create a function which accepts arrays of reals, no matter its concrete type. I would use:

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

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

I would like to call f([1,2,3]) or f([1.,2.,3.]) as long as the type of the element is Real.

I've read that you could promote or convert the array (p.eg f(convert(Array{Real}, [1, 2, 3])) or so) but I see that way really non-dynamic and tedious.

Is there any other alternative rather than getting rid of the strongly typed behaviour?

Thanks.

like image 988
TheSorcerer Avatar asked Mar 01 '16 08:03

TheSorcerer


2 Answers

To expand upon the solution by @user3580870, you can also use a typealias to make the function definition a little more succinct:

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

And then you can use the typealias in anonymous functions, too:

g = (x::RealArray) -> "something else with $x"
like image 193
mbauman Avatar answered Sep 28 '22 10:09

mbauman


Since there's been an updated since the orginal answer, the keyword typealias is gone so that the solution of @Matt B. would now be

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

I'll just put this here for the sake of completeness ;)

like image 26
rammelmueller Avatar answered Sep 28 '22 10:09

rammelmueller