Problem with map() and function.() when using structs

Hello!
I’ve run into this issue on multiple occasions, and I hoped someone here could help me out understand what’s going on.

So after defining instances of a struct and a function that takes input as the struct instance, the function cannot be applied element-wise to a single instance of a struct. The same problem occurs when using map(function, struct_instance). For vector of struct instances, everything works fine.

If that’s not a bug, how do I avoid having to define two methods of my function, or make an if statement each time I run the function?

struct test_struct
    a
    b
end

A = test_struct(1, 2)
B = test_struct(1, 2)

function test_func(object::test_struct)
    return object.a + object.b
end 

test_func.(A)
test_func.([A, B])
test_func(A)

map(test_func, A)
map.(test_func, A)
map(test_func, [A, B])
map.(test_func, [A, B])

Broadcasting and map is for containers - your test_struct is not a container. It doesn’t implement the AbstractArray interface:

https://docs.julialang.org/en/v1/manual/interfaces/#man-interface-array

That’s also why the mapping and broadcasting over an array of your struct works - an array has these methods defined.

1 Like

Adding Base.broadcastable(x::test_struct) = Ref(x) will fix your first set of errors. I’m not sure what you are trying to do with the other examples.