Reputation: 224
I'd like to write a function that can take both a DataArray and a standard Array in Julia. Actually, I'd like to write to methods for a function -- one that takes two vector-like structures as parameters and one that takes two matrix-like parameters.
Since Arrays and DataArrays are basically the same, only that a DataArray allows for NA values, I really do not want to write 4 versions of each function, just to incorporate all different combinations of Array and DataArray parameters. Right now, I use the following six (!) functions, to achieve my goal:
function covar_to_intensity{T<:Number}(covariates::Array{T, 1}, coefficients::Array{T, 1})
try
return(exp(covariates' * coefficients)[1])
catch
error("Multiplication of covariates and coefficients not possible.")
end
end
function covar_to_intensity{T<:Number}(covariates::Array{T, 2}, coefficients::Array{T, 2})
try
return(exp(covariates * coefficients))
catch
error("Multiplication of covariates and coefficients not possible.")
end
end
function covar_to_intensity{T<:Number}(covariates::DataArray{T, 1}, coefficients::DataArray{T, 1})
try
return(exp(covariates' * coefficients)[1])
catch
error("Multiplication of covariates and coefficients not possible.")
end
end
function covar_to_intensity{T<:Number}(covariates::DataArray{T, 2}, coefficients::DataArray{T, 2})
try
return(exp(covariates * coefficients))
catch
error("Multiplication of covariates and coefficients not possible.")
end
end
function covar_to_intensity{T<:Number}(covariates::Array{T, 1}, coefficients::DataArray{T, 1})
try
return(exp(covariates' * coefficients)[1])
catch
error("Multiplication of covariates and coefficients not possible.")
end
end
function covar_to_intensity{T<:Number}(covariates::Array{T, 2}, coefficients::DataArray{T, 2})
try
return(exp(covariates * coefficients))
catch
error("Multiplication of covariates and coefficients not possible.")
end
end
I'm aware that this might be an inefficient way to compute these products, but I also have a general interest regarding how to write functions taking both Arrays and DataArrays.
Thanks!
Upvotes: 2
Views: 1066
Reputation: 2929
In general, you can define methods for AbstractArray
:
function covar_to_intensity{T<:Number}(covariates::AbstractVector{T}, coefficients::AbstractVector{T})
try
return exp(covariates * coefficients)
catch
error("Multiplication of covariates and coefficients not possible.")
end
end
function covar_to_intensity{T<:Number}(covariates::AbstractMatrix{T}, coefficients::AbstractMatrix{T})
try
return exp((covariates' * coefficients)[1])
catch
error("Multiplication of covariates and coefficients not possible.")
end
end
Upvotes: 2