Error broadcasting a function for a custom type

In the DaysCount package there is the following function:

abstract type DayCount end
struct Actual365Fixed <: DayCount end
    
function yearfrac(startdate, enddate, ::Actual365Fixed)
    return Dates.value(enddate - startdate) /365
end

When trying to broadcast the above function with:

using Dates
startdate = Date(2020,11,3)
enddate = [Date(2021,1,1),Date(2021,2,2)]
yearfrac.(startdate, enddate, Actual365Fixed())

one gets the following error:

ERROR: LoadError: MethodError: no method matching length(::Actual365Fixed)

What am I doing wrong? Thanks in advance.

You just need to tell the broadcast call to treat your Actual365Fixed as a scalar, rather than a collection, by wrapping it in a Ref(). See Is there a reason a `MersenneTwister` value is not broadcastable? - #13 by stevengj for more info.

2 Likes

You just need to tell the broadcast call to treat your Actual365Fixed as a scalar, rather than a collection, by wrapping it in a Ref()

It works perfectly. Thank you very much!