# Type assertion?

**URL:** <https://discourse.julialang.org/t/type-assertion/35950>\
**Category:** New to Julia\
**Created:** [March 13, 2020, 10:42pm UTC](https://discourse.julialang.org/t/type-assertion/35950 "2020-03-13T22:42:19Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![BLI](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/bli/32/37206_2.png) [@BLI](https://discourse.julialang.org/u/BLI)\
**Post date:** [March 13, 2020, 10:42pm UTC](https://discourse.julialang.org/t/type-assertion/35950/1 "2020-03-13T22:42:19Z")

</div>

I’m playing around with a function where the argument should be a vector of same-sized vectors, i.e.,

```julia
v = [v1,v2,v3,...,vN]

```

where `v1`, …, `vN` etc. are vectors containing scalar elements, and of the same size.

How can I test for this in the function call? I tried with:

```julia
function myfunc(v::Vector{Vector{Number}})
...
end

```

but that didn’t work. [And it wouldn’t even have checked that the elements of `v` were vectors of the same size…]

Question:

- Is there a way to specify the structure of the argument I expect?
- Would it be better to just forget about asserting the argument type, let misuse of the function lead to an error message, and “force” the user (i.e., myself) to re-read the documentation?

---

<div class="post-metadata">

**Author:** ![tamasgal](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamasgal/32/27946_2.png) [@tamasgal](https://discourse.julialang.org/u/tamasgal)\
**Post date:** [March 13, 2020, 10:47pm UTC](https://discourse.julialang.org/t/type-assertion/35950/2 "2020-03-13T22:47:48Z")

</div>

It sounds like you should delegate this “check” to the dispatch system by e.g. creating a type with your desired property (equally sized subarrays) and forcing the user to use those. The consistency check can be done inside the constructors of the type.

---

<div class="post-metadata">

**Author:** ![kristoffer.carlsson](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/kristoffer.carlsson/32/22_2.png) [@kristoffer.carlsson](https://discourse.julialang.org/u/kristoffer.carlsson)\
**Post date:** [March 13, 2020, 10:51pm UTC](https://discourse.julialang.org/t/type-assertion/35950/3 "2020-03-13T22:51:17Z")

</div>

> [@BLI](#):
>
> where `v1` , …, `vN` etc. are vectors containing scalar elements, and of the same size.

`Vector`s don’t have their sizes as part of their types so you cannot type annotate this.

In some cases you could take a `Matrix` instead of a `Vector` since all the columns in a `Matrix` has the same number of rows but that might not be applicable in your case.

---

<div class="post-metadata">

**Author:** ![tamasgal](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamasgal/32/27946_2.png) [@tamasgal](https://discourse.julialang.org/u/tamasgal)\
**Post date:** [March 13, 2020, 10:59pm UTC](https://discourse.julialang.org/t/type-assertion/35950/4 "2020-03-13T22:59:05Z")

</div>

What I meant is a type which keeps e.g. a flat array with all the values and the number of elements `N` in their fields.  
A constructor for this type then would then look something like this `Vector(vectors...) = ...` which checks the length for equality and set’s `N` and the concatenated values.  
Finally the get index method is defined which does the magic slicing behind the scenes and returns the sub-arrays.

It’s just a rough idea… 😉

edit: just realised I was doing too much with awkward arrays in Python today, just storing the Vector of Vectors is perfectly fine. In the constructor then the mentioned check… then use that as type in the function argument.

---

<div class="post-metadata">

**Author:** ![BLI](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/bli/32/37206_2.png) [@BLI](https://discourse.julialang.org/u/BLI)\
**Post date:** [March 13, 2020, 11:01pm UTC](https://discourse.julialang.org/t/type-assertion/35950/5 "2020-03-13T23:01:34Z")

</div>

Thanks! I will think it over tomorrow… I haven’ tried to define my own types yet.

---

<div class="post-metadata">

**Author:** ![tamasgal](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamasgal/32/27946_2.png) [@tamasgal](https://discourse.julialang.org/u/tamasgal)\
**Post date:** [March 13, 2020, 11:03pm UTC](https://discourse.julialang.org/t/type-assertion/35950/6 "2020-03-13T23:03:19Z")

</div>

Having your own types in Julia is one of the greatest fun in this language 😉

---

<div class="post-metadata">

**Author:** ![BLI](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/bli/32/37206_2.png) [@BLI](https://discourse.julialang.org/u/BLI)\
**Post date:** [March 13, 2020, 11:24pm UTC](https://discourse.julialang.org/t/type-assertion/35950/7 "2020-03-13T23:24:36Z")

</div>

What I look into is just a convenience function for converting back and forth between sampled based data and time series data, i.e.,

[[y\_1(t\_1),\ldots,y\_{n\_y}(t\_1)],\ldots,[y\_1(t\_N),\ldots,y\_{n\_y}(t\_N)]] \\ \updownarrow\\ [[y\_1(t\_1),\ldots,y\_1(t\_N)],\ldots,[y\_{n\_y}(t\_1),\ldots,y\_{n\_y}(t\_N)]]

The following function does it:

```julia
function vec2vec(v)
    return [getindex.(v,i) for i in 1:lastindex(v[1])]
end

```

OK – not an earth shattering function; it is so simple that perhaps it is not even worth making a function out of it. But it is convenient: e.g., if `sol` is the solution of a differential equation solver, `vec2vec(sol[:])` would transform the solution to something that is easier to plot — for the cases where I don’t want to use the built-in interpolation.

So, this function only works (properly) if the elements of the vector are vectors of equal size… so I was thinking of adding type assertion to make sure that `v` (argument of `vec2vec`) had the right type before I start to operate on the data.

---

<div class="post-metadata">

**Author:** ![tamasgal](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamasgal/32/27946_2.png) [@tamasgal](https://discourse.julialang.org/u/tamasgal)\
**Post date:** [March 13, 2020, 11:40pm UTC](https://discourse.julialang.org/t/type-assertion/35950/8 "2020-03-13T23:40:09Z")

</div>

You can create a dead simple function and an assertion which shows a meaningful message to the user. Here is an example with `@assert`

```julia
equal_lengths(v) = all(x->length(x)==length(first(v)), v[2:end])

function vec2vec(v)
    @assert equal_lengths(v)
    return [getindex.(v,i) for i in 1:lastindex(v[1])]
end

```

and here instead of `@assert` an `error`:

```julia
function vec2vec(v)
    equal_lengths(v) || error("The vectors must have equal lengths.")
    return [getindex.(v,i) for i in 1:lastindex(v[1])]
end

```

---

<div class="post-metadata">

**Author:** ![BLI](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/bli/32/37206_2.png) [@BLI](https://discourse.julialang.org/u/BLI)\
**Post date:** [March 14, 2020, 9:03pm UTC](https://discourse.julialang.org/t/type-assertion/35950/9 "2020-03-14T21:03:28Z")

</div>

I’m trying to understand your `equal_lengths()` function… (since I haven’t used it before):

> [@tamasgal](#):
>
> equal\_lengths(v) = all(x-\>length(x)==length(first(v)), v[2:end])

An equivalent function would be the following, right?

```julia
equal_lengths(v) = all( [length(x) == length(first(v)) for x in v[2:end] ] )

```

Your version appears to be a little more efficient based on `BenchmarkTools`– why?

Also, is there an advantage in using `first(v)` over `v[1]`?

---

<div class="post-metadata">

**Author:** ![kristoffer.carlsson](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/kristoffer.carlsson/32/22_2.png) [@kristoffer.carlsson](https://discourse.julialang.org/u/kristoffer.carlsson)\
**Post date:** [March 14, 2020, 9:29pm UTC](https://discourse.julialang.org/t/type-assertion/35950/10 "2020-03-14T21:29:44Z")

</div>

> [@BLI](#):
>
> Your version appears to be a little more efficient based on `BenchmarkTools` – why?

Your version is allocating a new array unnecessarily.

> [@BLI](#):
>
> Also, is there an advantage in using `first(v)` over `v[1]` ?

Some custom arrays might not start with `1`.

---

<div class="post-metadata">

**Author:** ![BLI](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/bli/32/37206_2.png) [@BLI](https://discourse.julialang.org/u/BLI)\
**Post date:** [March 15, 2020, 12:42pm UTC](https://discourse.julialang.org/t/type-assertion/35950/11 "2020-03-15T12:42:47Z")

</div>

Ah, ok…

- my version actually creates a vector of length `length(v)-1` filled boolean values, and when created, checks whether `all` values are true. While tamasgal’s version does not create this vector, but instead checks iteratively?
- OK – I get that some custom arrays may not start with 1. But if they don’t start with one, does it then make sense to test against `v[2:end]`? What if the array start with 0… won’t I then miss testing against `v[1]`?

---

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [March 15, 2020, 3:01pm UTC](https://discourse.julialang.org/t/type-assertion/35950/12 "2020-03-15T15:01:18Z")

</div>

> [@BLI](#):
>
> What if the array start with 0… won’t I then miss testing against `v[1]` ?

Yes, you probably would. From 1.4, you can use something like

```julia
all(x->length(x)==length(first(v)), v[(begin + 1):end])

```

For versions before that, consider `firstindex(v) + 1`.

---

<div class="post-metadata">

**Author:** ![Skoffer](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/skoffer/32/378_2.png) [@Skoffer](https://discourse.julialang.org/u/Skoffer)\
**Post date:** [March 15, 2020, 3:14pm UTC](https://discourse.julialang.org/t/type-assertion/35950/13 "2020-03-15T15:14:00Z")

</div>

Correct me if I am wrong, but benefits of starting from `begin + 1` are outweighed by the fact that `v[begin + 1:end]` allocates. So, one should either use `@view` or just use all vectors (ok, you’ve got +1 `true` what’s wrong with that?)

```julia
julia> v = [zeros(100) for _ in 1:200]
julia> @btime all(x->length(x)==length(first($v)), $v[2:end])
357.779 ns (1 allocation: 1.77 KiB)

julia> @btime all(x->length(x)==length(first($v)), $v)
137.869 ns (0 allocations: 0 bytes)

julia> @btime all(x->length(x)==length(first($v)), @view($v[2:end]))
171.277 ns (0 allocations: 0 bytes)

```

---

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [March 15, 2020, 3:32pm UTC](https://discourse.julialang.org/t/type-assertion/35950/14 "2020-03-15T15:32:11Z")

</div>

> [@Skoffer](#):
>
> benefits of starting from `begin + 1` are outweighed by the fact that `v[begin + 1:end]` allocates

Views and indexing are (should be) orthogonal, in the sense that you should be able to modify the example above by adding a `@view`. That said, it looks like `@view` was not updated for [#33946](https://github.com/JuliaLang/julia/pull/33946/).

Incidentally, I think that introducing micro-optimizations like this, especially in _First steps_, may just be derailings the topic for no good reason. Also, `2:end` is broken for generalized indexing, as noted by @BLI. If you really want views at this point, just use

```julia
view(v, (firstindex(v) + 1):lastindex(v))

```

or something equivalent.

---

<div class="post-metadata">

**Author:** ![BLI](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/bli/32/37206_2.png) [@BLI](https://discourse.julialang.org/u/BLI)\
**Post date:** [March 15, 2020, 3:41pm UTC](https://discourse.julialang.org/t/type-assertion/35950/15 "2020-03-15T15:41:48Z")

</div>

> [@Skoffer](#):
>
> @btime all(x-\>length(x)==length(first($v)), $v[2:end])

I’ve noticed that some of you use the construct `$v` instead of `v` sometimes. It seems to have a big impact:

```julia
julia> @btime all(x->length(x)==length(first($v)), v)
  128.941 ns (1 allocation: 16 bytes)
true

julia> @btime all(x->length(x)==length(first($v)), $v)
  7.500 ns (0 allocations: 0 bytes)

```

[I used a different `v` vector than you], but

- What does the $ syntax actually mean here (not interpolation, I guess…)?, and
- When should be used and when not?

---

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [March 15, 2020, 3:50pm UTC](https://discourse.julialang.org/t/type-assertion/35950/16 "2020-03-15T15:50:06Z")

</div>

> [@BLI](#):
>
> - What does the $ syntax actually mean here (not interpolation, I guess…)?, and
> - When should be used and when not?

[https://github.com/JuliaCI/BenchmarkTools.jl/blob/master/doc/manual.md#interpolating-values-into-benchmark-expressions](https://github.com/JuliaCI/BenchmarkTools.jl/blob/master/doc/manual.md#interpolating-values-into-benchmark-expressions)

---

<div class="post-metadata">

**Author:** ![BLI](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/bli/32/37206_2.png) [@BLI](https://discourse.julialang.org/u/BLI)\
**Post date:** [March 15, 2020, 4:44pm UTC](https://discourse.julialang.org/t/type-assertion/35950/17 "2020-03-15T16:44:20Z")

</div>

The reference talks about `$` “interpolating values into benchmark expressions”.

- Does this imply that this interpolation is only used within the context of _benchmarking_, and that for regular code in actual use (e.g., when not prefaced by a macro such as `@btime`), it should not be used?
- In other words, this interpolation is only inserted in order to get a best possible idea of the performance?

---

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [March 15, 2020, 5:03pm UTC](https://discourse.julialang.org/t/type-assertion/35950/18 "2020-03-15T17:03:05Z")

</div>

No. [Interpolation](https://docs.julialang.org/en/v1/manual/metaprogramming/#Interpolation-1) is a syntactic feature of Julia, used for various things. Here the `BenchmarkTools` macros ~~kind of hijack~~ use of it for a specific purpose to provide a compact syntax for something that is useful.

_Why_ it is needed is explained in the link above, the syntax is orthogonal to that; it’s just a syntax and has nothing more to do with interpolation in Julia for other purposes. You could design your own macros that pick out a `$` and do something else to it.

---

<div class="post-metadata">

**Author:** ![dpsanders](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dpsanders/32/3573_2.png) [@dpsanders](https://discourse.julialang.org/u/dpsanders)\
**Post date:** [March 15, 2020, 5:24pm UTC](https://discourse.julialang.org/t/type-assertion/35950/19 "2020-03-15T17:24:35Z")

</div>

If each individual vector in your vector is reasonably small then this is a perfect situation to use “static vectors” from the `StaticArrays.jl` package. “Static” here means that the length of the vector _is_ encoded in the typed:

```julia
julia> using StaticArrays

julia> v1 = SVector(3, 4)
2-element SArray{Tuple{2},Int64,1,2} with indices SOneTo(2):
 3
 4

julia> v2 = SVector(5, 6)
2-element SArray{Tuple{2},Int64,1,2} with indices SOneTo(2):
 5
 6

julia> v = [v1, v2]
2-element Array{SArray{Tuple{2},Int64,1,2},1}:
 [3, 4]
 [5, 6]

julia> f(v::Vector{SVector{N,T}}) where {N,T} = N
f (generic function with 1 method)

julia> f(v)
2

```

---

<div class="post-metadata">

**Author:** ![BLI](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/bli/32/37206_2.png) [@BLI](https://discourse.julialang.org/u/BLI)\
**Post date:** [March 15, 2020, 5:48pm UTC](https://discourse.julialang.org/t/type-assertion/35950/20 "2020-03-15T17:48:04Z")

</div>

> [@BLI](#):
>
> Does this imply that this interpolation

“this interpolation” was meant to refer to the use of `$` within benchmarking. I know interpolation is a standard feature for strings.

In any way, when running the commands _without_ the BenchmarkTools.jl macro statement (`@btime`), the command crashed. Which means that _this_ use of interpolation does not work outside of the BenchmarkTools.jl package (e.g.,

```julia
@time all(x->length(x)==length(first($v)), $v)

```

crashes.)

So when I create a function for actual use (and not for benchmarking), I need to remove the interpolation symbol in the code.

[Next page](https://discourse.julialang.org/t/type-assertion/35950.md?page=2)
