Pass view to function

Hello,

Suppose I define a new type

struct foo
    x::Int
end

and I create a vector

foos = [foo(3), foo(2), foo(9), foo(7)]

Now, I want a function that I could call as

bar(view(foos, 3:4))

or as

bar(view(foos, [2,4]))

or as

bar(view(foos, :)).

What is the best way to achieve that?

Thank!

function bar(x)
  # x is the view
end

This auto-specializes on the type so there’s no performance left behind here.

2 Likes

Depends what you want to achieve. Possibly the best approach is to define bar(x::AbstractVector). If you want to restrict it to views specialize on SubArray. EDIT: of course if you don’t need to dispatch on the type you can just do what @ChrisRackauckas suggests above.

In fact, what I want to do is to use that function with an other type. So, I want something like

struct bar
    y::This is a view of a Vector{foo}
end

and to be able to call a constructor as I did in my original post.

Is it still a good idea to define it without specifying the type of y?

Try:

struct Bar{V <: AbstractVector{foo}}
  y::V 
end

which will let you create a Bar for any kind of vector of foo (including a regular Vector{foo} or a view into such a vector, etc.).

This is now different. Types should be strictly typed in order to get performance. You should do something like:

struct bar{T}
    y::T
end

to leave it open but still get performance, or

struct bar{T<:AbstractArray}
    y::T
end

etc. to place a check (note, there’s no performance difference though, it’s just a safety check).

2 Likes

Good, thank for the answer. That is exactly what I needed.