how to Display Tuple{Float64, Bool}

Viewed 147

I would like that boolean part of Tuple are displayed as such (and not an Integer or a Float) when part of a Matrix. Here the code:

a = [(1., true) (1.5 , true) ; (1.5 , false) (-5.5 , false) ]
2×2 Matrix{Tuple{Float64, Bool}}:
 (1.0, 1)  (1.5, 1)
 (1.5, 0)  (-5.5, 0)

However I was hoping for the following result:

2×2 Matrix{Tuple{Float64, Bool}}:
 (1.0, true)  (1.5, true)
 (1.5, false)  (-5.5, false)

I guess I am missing something in Julia's type; any help is appreciated.

By accident I realized that:

b = [(1., true) (1.5 , true) ; (false, 1.5) (false, -5.5) ]
2×2 Matrix{Tuple{Real, Real}}:
 (1.0, true)   (1.5, true)
 (false, 1.5)  (false, -5.5)

Display the Boolean as I would have expected for a (the first case). It is also unexpected that the Booleans are displayed as such when the Tuple's type is Tuple{Real, Real}. Again I feel that I am missing something; any pointer to a specific part of the documentation is welcomed. I am using Julia 1.6.1.

1 Answers

By default, Julia shows Bool type values in arrays like 0 and 1, making displaying more compact. And that is done for compatibility with bit array (which saves boolean values in one bit). e.g.:

julia> [true, false]
2-element Vector{Bool}:
 1
 0

Since we know the type of the array's elements is Bool, we understand that 1 is a true, and 0 is false.

But 0 or 1 is used when that is obvious from the type that those are boolean values. For your first case, tuple of float and boolean, and that was obvious that 1 is for true and 0 for false.

When creating arrays from values, Julia uses a common type for all values, which is Real. But for the second case that would not be clear: 1 is true, or 1 is an integer one. That is why Julia displays true and false for the second case.

If you want to use a type that could contain Bool or Float64 only, you can do it explicitly with Union{Float64, Bool}.

Thus if you want to show true or false, you could explicitly set Union type:

julia> a = Tuple{Union{Float64, Bool}, Union{Float64, Bool}}[(1., true) (1.5 , true) ; (1.5 , false) (-5.5 , false) ]
2×2 Matrix{Tuple{Union{Bool, Float64}, Union{Bool, Float64}}}:
 (1.0, true)   (1.5, true)
 (1.5, false)  (-5.5, false)

Update: This example only for the sake of explanation. If the second element in your tuple supposed to contain only Bool values, changing its type to Union{Float64,Bool} may dramatically affect performance.

Related