Different modules with nested structures

Koen
Sun, 23 Jul 2023 21:03:30 +0000
General Usage

Consider two functions, function Y and function Z. The parameter values of these functions are stored in two different structures, ParametersY and ParametersZ. Suppose the functions are nested, where Z uses Y. Then it seems logical to nest the structures as well, where ParametersY is included as a field in ParametersZ. Suppose the structures ParametersY and ParametersZ are defined in two separate modules.
The first module is:

module ModuleY
struct ParametersY
	a::Int64
end
export ParametersY
end

The second module is:

module ModuleZ
include(“ModuleY.jl”)
using .ModuleY
struct ParametersZ
	parent::ParametersY
	b::Int64
end
export ParametersZ
end

If you then do the following:

include(“ModuleY.jl”)
using .ModuleY
include(“ModuleZ.jl”)
using .ModuleZ
parsY = ParametersY(5)
parsZ = ParametersZ(parsY,3)

you get the following error message:

ERROR: MethodError: Cannot `convert` an object of type ParametersY to an object of type Main.ModuleZ.ModuleY.ParametersY

This can be solved by adding ParametersY to the export of ModuleZ, and then defining parsY and parsZ as follows:

parsY = ModuleY.ParametersY(5)
parsZ = ParametersZ(ModuleZ.ParametersY(5),3)

But with complex code, with several functions that are nested in each other, this may easily become very cumbersome. Isn’t there an easier way to go ahead? The ultimate goal is to get a library of functions that may refer to other functions and structures to store their parameter values (some of which may therefore be used by other functions if functions are nested).

4 posts - 3 participants