How do I create a new Array-like type with only ints and strings?

Hi there!

As am heading towards understanding the type system of Julia, I seem to not be able to do such a thing as to create-define a container type that would include only strings and integers.

Could anyone drop me the relevant code line? It does not seem there is somewhere in the docu that makes this easy…(although I have to admit that Julia’s documentation is one of the most straightforward I have seen and congrats for that!)

Any response with even a short explanation would be greatly appreciated!

Best!

Alex

1 Like

What about Array{Union{Int,String},2} (where 2 makes it a 2d array)

2 Likes

Thanks a lot for the quick response!

So, following the union type section of the docu, the following 2 lines should work as expected, right?

IntString = Array{Union{Int,String},2}
[23 "dd"; "er" 24] :: IntString

Why do I receive the message below?

ERROR: TypeError: in typeassert, expected Array{Union{Int64, String},2}, got Array{Any,2}
Stacktrace:
 [1] top-level scope at none:0

There is something missing in my knowledge base related to the scoping and I still cannot figure that out…sorry, for the elementary level of my question…

Thanks again!

Alex

In practice, an Array{Union{Int,String},2} often won’t be faster than a Array{Any,2} so it doesn’t really matter. The reason [23 "dd"; "er" 24] has eltype Any is that it is the only direct super-type of Int and String. Also, just wondering, why do you want to do this?

1 Like

Hmm…Thanks!
What if I wanted to create a container type that is populated only with elements of these specific two types (and exclude booleans, for instance)?
Basically, am experimenting these days, since I am thinking of various (research) domain-specific scenarios related to a research project I got funded recently. In general am charmed from the experience of learning Julia and trying to dig in a bit more and explore the possibility of using it for the project’s data analysis stage.

x::Array{Union{Int,String},2}= [23 "dd"; "er" 24] will work in a function (typed globals aren’t supported in Julia yet). That said, doing something like this is almost always a bad idea. Fast code requires type stability.

1 Like

Am sure as am learning more about Julia I will be able to grasp more of the ideas related to type stability and performance!

Thanks again!

Alex

You can also take this approach:

julia> IntString = Union{Int,String}
Union{Int64, String}

julia> IntString[23 "dd"; "er" 24]
2×2 Array{Union{Int64, String},2}:
 23        "dd"
   "er"  24

See this section of the docs.

3 Likes

Thanks a lot @CameronBieganek! That is exactly what I was hoping for! Still on my way of digging into the documentation…

Best!

Alex

1 Like